-
题目:
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5 -
注意:是重复的节点一概不保留,所以要保存重复区域的前驱节点,同时注意将重复的区域一直遍历到最后,这样就跳过了整个重复区域
-
Code
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* deleteDuplication(ListNode* pHead){ if(pHead == NULL) return NULL; ListNode* pre = NULL; ListNode* cur = pHead; while(cur){ if(cur->next && cur->val == cur->next->val){ int tmp = cur->val; while(cur->next && cur->next->val == tmp){ cur = cur->next; } if(pre == NULL){ pHead = cur->next; } else { pre->next = cur->next; } } else{ pre = cur; } cur = cur->next; } return pHead; } };
【剑指Offer】删除链表中重复的结点
最新推荐文章于 2021-03-16 22:05:34 发布