剑指offer——(30)删除链表中重复的结点

版权声明:本文自由转载,转载请注明出处。 https://blog.csdn.net/qq_38071429/article/details/85929641

在这里插入图片描述
难受啊 调了快三个小时 明明很简单 思路也很清晰 可跑出来的结果就是和我在纸上走一遍的结果不一样。。

//import java.util.ArrayList;

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 temp = new ListNode(-1);
        ListNode result = temp;
        int tempVal = 0;
        boolean bo = false;
        while(pHead != null) {
            tempVal = pHead.val;
            if(pHead.next == null) break;
            boolean boo = false;
            pHead = pHead.next;
            //System.out.print("temp"+temp.val+" ");
            while (pHead.val == tempVal) {
                //System.out.print("temp"+temp.val+" ");
                boo = true;
                if(pHead.next == null) {
                    bo = true;
                    break;
                }
                pHead = pHead.next;
            }
            if (boo == false) {
                temp.next = new ListNode(tempVal);
                temp = temp.next;
            }
        }
        if(bo != true ){
            temp = temp.next = new ListNode(tempVal);
        }
        return result.next;

    }

    public static void main(String[] args) {
        ListNode Node = new ListNode(1);
        ListNode Node2 = new ListNode(1);
        ListNode Node3 = new ListNode(2);
        ListNode Node4 = new ListNode(3);
        ListNode Node5 = new ListNode(3);
        ListNode Node6 = new ListNode(4);
        ListNode Node7 = new ListNode(5);
        ListNode Node8 = new ListNode(5);
        Node.next = Node2;
        Node2.next = Node3;
        Node3.next = Node4;
        Node4.next = Node5;
        Node5.next = Node6;
        Node6.next = Node7;
        Node7.next = Node8;
        Node8.next = null;
        ListNode result = new Solution().deleteDuplication(Node);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }
}



猜你喜欢

转载自blog.csdn.net/qq_38071429/article/details/85929641
今日推荐