问题描述(LeetCode):
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
意思就是只要有重复的节点都去掉。这主要考察的是链表删除节点的操作,以及考虑问题的是否周全。
大致思路如下:
1 定义一个当前节点指针cur,只要一判断到某节点和其之后的节点的值相同,就用一个变量把该值保存下来,然后从当前节点开始,把所有相同值的节点都删除掉;
2 为了拼接由于1中删除节点产生的断层,需要一个节点指针pre。只要判断出当前节点与它下一个节点的值不同,便可把当前节点指针赋值给pre。
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
意思就是只要有重复的节点都去掉。这主要考察的是链表删除节点的操作,以及考虑问题的是否周全。
大致思路如下:
1 定义一个当前节点指针cur,只要一判断到某节点和其之后的节点的值相同,就用一个变量把该值保存下来,然后从当前节点开始,把所有相同值的节点都删除掉;
2 为了拼接由于1中删除节点产生的断层,需要一个节点指针pre。只要判断出当前节点与它下一个节点的值不同,便可把当前节点指针赋值给pre。
代码如下(思路还是有点乱,思路清晰的话,代码应该可以优化):
/**
* 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 == NULL || head->next == NULL)
return head;
int temp = 0;
ListNode* cur = head;
head = NULL;
ListNode* pre = head;
while(cur != NULL)
{
if(cur->next == NULL)
break;
if(cur->val != cur->next->val)
{
if(head == NULL)
head = cur;
pre = cur;
cur = cur->next;
}
else
{
temp = cur->val;
while(cur != NULL && cur->val == temp)
{
ListNode *temp = cur;
cur = cur->next;
delete temp;
}
if(pre == head && head == NULL)
{
pre = cur;
}
else
pre->next = cur;
}
}
if(cur != NULL && head == NULL)
head = cur;
return head;
}
};