文章目录
  1. 1. Remove Duplicates from Sorted List
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Remove Duplicates from Sorted List

题目

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

思路

cur表示当前结点,cur->next表示下一结点。若cur->val等于cur->next->val,则删除cur->next这一结点,按下述操作cur->next=cur->next->next。否则cur=cur->next。

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head)
return NULL;
ListNode *cur=head;
while(cur->next){
if(cur->next->val==cur->val)
cur->next=cur->next->next;
else
cur=cur->next;
}
return head;
}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
dummy=ListNode(-1)
dummy.next=head
cur=dummy.next
while cur and cur.next:
if cur.val==cur.next.val:
cur.next=cur.next.next
else:
cur=cur.next
return dummy.next
文章目录
  1. 1. Remove Duplicates from Sorted List
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题