剑指Offer-删除链表中重复的节点
题目:
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路1:
为方便操作,首先为链表加入一个头节点。基本思路为有3个指针,分别为pre,current,nextnode,它们之间的关系为pre->next = current;current->next = nextnode。
若current的数值大小与nextnode相同,则nextnode不断向后移动直至current的数值大小与nextnode不同,令current=nextnode,pre->next = current。若nextnode为NULL,则nextnode无需再向后移动,否则nextnode向后移动且current->next = nextnode。
若current的数值大小与nextnode不同,则pre,current,nextnode均向后移动一位并再次判断大小。
代码1:
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 ListNode* deleteDuplication(ListNode* pHead) { 13 ListNode *pre = new ListNode(-1); 14 pre->next = pHead; 15 ListNode *newhead = pre; 16 ListNode *current = pHead; 17 ListNode *nextnode = pHead->next; 18 while (current != NULL && nextnode != NULL) { 19 if (current->val == nextnode->val) { 20 while (nextnode != NULL && current->val == nextnode->val) { 21 nextnode = nextnode->next; 22 } 23 current = nextnode; 24 pre->next = current; 25 if (nextnode != NULL) { 26 nextnode = nextnode->next; 27 current->next = nextnode; 28 } 29 } else { 30 pre = pre->next; 31 current = current->next; 32 nextnode = nextnode->next; 33 } 34 } 35 return newhead->next; 36 } 37 };
思路2:
在思路1中,有3个指针分别为pre,current,nextnode,考虑可以去除nextnode,只用2个指针完成操作。
当current与current->next的大小相同时,记录下current的数值value,并向后移动current直至current的大小与value不同。将pre的下一个节点指向current。
当current与current->next的大小不同时,向后移动pre和current并再次检查。
代码2:
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 ListNode* deleteDuplication(ListNode* pHead) { 13 ListNode *pre = new ListNode(-1); 14 pre->next = pHead; 15 ListNode *newhead = pre; 16 ListNode *current = pHead; 17 while (current != NULL) { 18 if (current->next != NULL && current->val == current->next->val) { 19 int value = current->val; 20 while (current != NULL && current->val == value) { 21 current = current->next; 22 } 23 pre->next = current; 24 } else { 25 pre = current; 26 current = current->next; 27 } 28 } 29 return newhead->next; 30 } 31 };