剑指offer:删除链表中的重复节点

题目一:

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

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if (pHead == null || pHead.next == null) return pHead;
        ListNode head = pHead;
        ListNode pre = pHead;
        int flag = 0;
        while(head!=null&&head.next!=null){
            pre = head;
            head = head.next;
           // while(pre.val == head.val){
            //为防止尾节点也与前一个节点相同要加一个判断
            while(head!=null&&pre.val == head.val){
                head = head.next;
                flag = 1;
            }     
            if (flag ==1){
                if (head == null){
                    if (pre == pHead) return null;
                    //从头开始进行遍历找到当前的pre节点
                    ListNode newpre = pHead;
                    ListNode newhead = pHead;
                    while(newhead!=pre) {
                        newpre = newhead;
                        newhead = newhead.next;
                    }               
                    newpre.next = null;
                    pre = head;                  
                }else{
                    ListNode next = head.next;
                    pre.val = head.val;
                    pre.next = next;
                }            
                head = pre;
                flag = 0;
            }         
        }       
        return pHead;
    }
}

思考:为防止头结点重复,则可以为其加一个头结点,方便统一处理。

题目二:

保留重复的节点

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if (pHead == null || pHead.next == null) return pHead;
        ListNode head = pHead;
        ListNode pre = pHead;
        while(head.next!=null){
            pre = head;
            head = head.next;
            while(pre.val == head.val){
                head = head.next;
            }
            pre.next = head;
        }
        return pHead;
    }
}
发布了126 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zhpf225/article/details/103402650