劍指offer——(30)刪除連結串列中重複的結點
阿新 • • 發佈:2019-01-06
難受啊 調了快三個小時 明明很簡單 思路也很清晰 可跑出來的結果就是和我在紙上走一遍的結果不一樣。。
//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;
}
}
}