JZ76 删除链表中重复的结点(较难)

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

数据范围:链表长度满足1<=n<=1000  ,链表中的值满足 

进阶:空间复杂度 O(N) ,时间复杂度 O(N)

例如输入{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) {
        ListNode tempNode = new ListNode(-1);
        ListNode tail = tempNode;
        while (pHead != null){
            if (pHead.next == null || pHead.val != pHead.next.val){
                tail.next = pHead;
                tail = pHead;
            }
            while (pHead.next != null && pHead.val == pHead.next.val){
                pHead = pHead.next;
            }
            pHead = pHead.next;
        }
        tail.next = null;
        return tempNode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_47465999/article/details/121409929