删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

解题思路

这道题做了比较久……感觉有一点点难写。

主要看下面这幅图理解

思路图

先建一个头结点,返回的时候返回这个头结点。
再建两个临时结点p、q,p用来作存储结点,q用来跳过重复结点。如图中第二个q的位置,先判断p的下一个结点位置是否与q一样,不一样的话先把q的下一个结点位置存到p的下一个结点,这样就先跳过了前面的重复结点。如果p的下一个结点是一样的,那就是图中第二个p的位置那里,这个时候证明了当前的q结点是不重复的,此时p直接存储q结点。

1
2
3
4
5
6
7
8
9
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead == NULL || pHead->next == NULL) {
return pHead;
}
int first = -1;
if (pHead->val == first) {
first = -2;
}

ListNode *head = new ListNode(first);
head->next = pHead;

ListNode *p = head;
ListNode *q = head->next;

while (q != NULL) {
while ((q->next != NULL) && (q->val == q->next->val)) {
q = q->next;
}

if (p->next != q) {
q = q->next;
p->next = q;
} else {
p = q;
q = q->next;
}
}
return head->next;

}
};