問題:
給定一個排序鏈表,刪除所有重複的元素每個元素只留下一個。
樣例:
樣例 1: 輸入: null 輸出: null 樣例 2: 輸入: 1->1->2->null 輸出: 1->2->null 樣例 3: 輸入: 1->1->2->3->3->null 輸出: 1->2->3->null
python:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: head is the head of the linked list
@return: head of linked list
"""
def deleteDuplicates(self, head):
# write your code here
if head == None or head.next == None:
return head
curNode = head
while curNode.next != None:
if curNode.val == curNode.next.val:
curNode.next = curNode.next.next
continue
curNode = curNode.next
return head
C++:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: head is the head of the linked list
* @return: head of linked list
*/
ListNode * deleteDuplicates(ListNode * head) {
// write your code here
if(head == NULL || head->next == NULL)
{
return head;
}
ListNode *curNode = head;
while(curNode->next != NULL)
{
if(curNode->val == curNode->next->val)
{
curNode->next = curNode->next->next;
continue;
}
curNode = curNode->next;
}
return head;
}
};