版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目要求
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针
示例:
输入:1->2->2->3->4->4->5
输出:1->3->5
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */
解题思路
方法:
给三个指针 cur,next,prev,cur 指向第一个结点,若后移过程与 next 相等,删除 next 后 cur 再后移,直至 cur 与 next 不相等时,删除 cur ,cur 后移,prev 后移,next 后移,重新链接 prev 和新 cur,若后移过程中,cur 与 next 不相等,next、cur、prev 后移
解题演示
输入:1->2->2->3->4->4->5
输出:1->3->5
过程显示:
- cur 、prev、next 在开始时指向如图所示
- cur 、next、prev 始终后移,直到 cur = next
- 遍历链表当 cur = next 时,next 后移,删去原 next 值,继续比较
- 上一步操作直到 cur 与 next 不相等时,删去原 cur 值,使 cur 指向 next,next 指向 cur -> next,如图对两个 4 的删除步骤相同 ,当 cur、next 不相等时,cur 、next、prev 继续后移
- 当 cur -> next 指向空时,结束,返回新链表
解题代码
public class Solution { public ListNode deleteDuplication(ListNode pHead){ if (pHead == null || pHead.next == null) { return pHead; } ListNode head = new ListNode(Integer.MIN_VALUE); head.next = pHead; ListNode prev = head; ListNode cur = head.next; while (cur != null) { if (cur.next != null && cur.next.val == cur.val) { while (cur.next != null && cur.next.val == cur.val) { cur = cur.next; } cur = cur.next; prev.next = cur; } else { prev = cur; cur = cur.next; } } return head.next; } }