56 删除链表中重复的结点

题目要求:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

注意:从题干上举的例子来说,存在多个重复的结点. 还要注意链表是排序的

方法借鉴于:https://blog.csdn.net/lhl1124281072/article/details/79813458

 1 /*
 2  public class ListNode {
 3     int val;
 4     ListNode next = null;
 5     ListNode(int val) {
 6         this.val = val;
 7     }
 8 }
 9 */
10 public class Solution {
11     public ListNode deleteDuplication(ListNode pHead){
12         //创建新的头结点,是因为需要考虑头部元素上来就重复的情况
13         ListNode result = new ListNode(-1);
14         result.next = pHead;
15         //使用cur和next两个指针进行移动分析,hasDuplication变量来表明是否有重复结点
16         ListNode cur = result;
17         ListNode next = pHead;
18         boolean hasDuplication = false;
19         while(next!=null){
20             //next.next!=null不要忽略
21             while(next.next!=null && next.val== next.next.val){
22                 hasDuplication = true;
23                 next = next.next;
24             }
25             if(hasDuplication){//说明有重复节点,cur在动
26                 cur.next = next.next;
27             }else{            //没有重复节点,cur要往下走啊
28                 cur = next;
29             }
30             //下面语句是无论存不存在重复,都要执行
31             //上面的if else表明了cur怎么动,下面就是next怎么动
32             next = next.next;
33             hasDuplication = false;
34         }
35         return result.next;
36     }
37 }

 

扫描二维码关注公众号,回复: 6788437 查看本文章

猜你喜欢

转载自www.cnblogs.com/shareidea94/p/11156622.html