题解 | #删除链表中重复的结点#

删除链表中重复的结点

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef

import java.util.*;
/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if(pHead == null)return null;
        ListNode dummyHead = new ListNode(-1);
        ListNode newHead = dummyHead;

        while(pHead != null){
            if(pHead.next != null && pHead.next.val == pHead.val){
                //跳过该重复节点的所有元素
                while(pHead.next != null && pHead.val == pHead.next.val){
                    pHead = pHead.next;
                }
                //循环出来后,指向的是重复的最后一个元素,因而需要再往下取一个
                pHead = pHead.next;
            }else{
                newHead.next = pHead;
                newHead = pHead;
                pHead = pHead.next;
            }
        }
        //最后一个结果的next链需要断掉
        newHead.next = null;
        return dummyHead.next;
    }
}

全部评论

相关推荐

团子请爱我一次_十月...:不是戈门,干哪来了,这就是java嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务