题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
思路1:双指针非递归法。本题目的关键是要考虑到多种测试用例,例如重复的结点位于链表头部、中间、尾部。
思路2:递归法。
☆☆解法1.1
public class Solution { public ListNode deleteDuplication(ListNode pHead) { if (pHead == null) return null; ListNode pre = null; ListNode cur = pHead; while (cur != null){ if (cur.next != null && cur.val == cur.next.val){ while (cur.next != null && cur.val == cur.next.val){ cur = cur.next; } cur = cur.next; if (pre == null){ pHead = cur; }else{ pre.next = cur; } }else{ pre = cur; cur = cur.next; } } return pHead; } }
☆☆解法1.2(使用虚拟头节点)
public class Solution { public ListNode deleteDuplication(ListNode pHead) { if (pHead == null || pHead.next == null){ return pHead; } ListNode head = new ListNode(-1); head.next = pHead; ListNode pre = head; ListNode cur = head.next; while (cur != null){ if (cur.next != null && cur.val == cur.next.val){ while (cur.next != null && cur.val == cur.next.val){ cur = cur.next; } cur = cur.next; pre.next = cur; }else{ pre = pre.next; cur = cur.next; } } return head.next; // 虚拟头节点的下一个才是真实头节点 } }