题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }
注意要求:
1. 排序的链表:说明如果有重复的结点他们是连续存在的
2. 重复的结点不保留
思路一
使用递归法进行删除
实现
public ListNode deleteDuplication(ListNode pHead) { if (pHead == null || pHead.next == null) return pHead; ListNode next = pHead.next; if (pHead.val == next.val) { while (next != null && pHead.val == next.val) next = next.next; return deleteDuplication(next); } else { pHead.next = deleteDuplication(pHead.next); return pHead; } }
思路二
非递归思路,先创建一个头节点,然后迭代链表,每次判断当前结点和当前节点的下一节点值是否相同,如果相同就接着循环直到不相同,将不相同的结点插入到头节点之后。
实现
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; } pre.next = cur.next; }else{ pre = pre.next; } cur = cur.next; } return Head.next; } }
思路参考:
https://www.nowcoder.com/discuss/198840
https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef?f=discussion
如果该题目是删除重复保留第一个(一开始理解错误题目):
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ import java.util.HashSet; public class Solution { public ListNode deleteDuplication(ListNode pHead) { // 该做法重复的结点保留第一个 if(pHead == null || pHead.next == null) return pHead; HashSet hs = new HashSet(); ListNode tmpHead = pHead; ListNode prio = null; while(tmpHead != null){ boolean res = hs.add(tmpHead.val); if(res == false){ prio.next = tmpHead.next; }else{ prio = tmpHead; } tmpHead = tmpHead.next; } return pHead; } }