刪除排序連結串列中的重複數字 II
阿新 • • 發佈:2019-01-03
2017.11.1
果然一遇到連結串列就剪不清理還亂。一會兒就徹底懵了。
大致思路就是先判斷有沒有重複的,
如果有重複的,就全部刪除
如果沒有重複的,就下一個。
呵呵,道理我都懂啊,我就是寫不出來程式碼啊
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /* * @param head: head is the head of the linked list * @return: head of the linked list */ public static ListNode deleteDuplicates(ListNode head) { // write your code here if(head == null ||head.next == null){ return head; } ListNode myHead = new ListNode(-1); myHead.next = head; //表示當前遍歷節點的上一個節點 ListNode flag = myHead; //當前的值 while(head!= null){ int tmp = head.val; if(head.next == null || head.next.val != tmp){ flag.next = head; flag = head; head = head.next; continue; } while(head != null && head.val == tmp){ head = head.next; } flag.next = head; } return myHead.next; } }