[算法]删除链表中重复的节点

题目描述

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

思路

新建一个头节点,向后进行重复查找判断。

代码

/*
 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 || pHead.next == null){
            return pHead;
        }
        ListNode head = new ListNode(-1);
        head.next = pHead;
        ListNode p = head;
        ListNode q = head.next;
        while(q != null){
            while(q.next != null && q.next.val == q.val){
                q = q.next;
            }
            if(p.next == q){
                p = q;
                q = q.next;
            }else{
                q = q.next;
                p.next = q;
            }
        }
        return head.next;
    }
}
原文地址:https://www.cnblogs.com/DarrenChan/p/10247391.html