lintcode,刪除排序連結串列中的重複數字 II
阿新 • • 發佈:2019-02-08
給定一個排序連結串列,刪除所有重複的元素只留下原連結串列中沒有重複的元素。
樣例
給出 1->2->3->3->4->4->5->null,返回 1->2->5->null
給出 1->1->1->2->3->null,返回 2->3->null
一刷ac
解題思路:設定一個標誌位代表是否存在重複,然後拼接連結串列。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of the linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
if(head == null) return head;
ListNode dummy = new ListNode(0);
ListNode node = dummy;
int flag = 0;
while(head != null){
if(head.next != null){
if(head.next.val == head.val){
head = head.next;
flag = 1;
}else{
if(flag == 0){
node.next = head;
node = node.next;
head = head.next;
}else {
head = head.next;
flag = 0;
}
}
}
else{
if(flag == 0){
node.next = head;
node = node.next;
head = head.next;
}else{
node.next = null;
head = head.next;
}
}
}
return dummy.next;
}
}
簡潔版
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of the linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
if(head == null) return head;
ListNode dummy = new ListNode(0);
ListNode node = dummy;
dummy.next = head;
while(head != null){
while(head.next != null && head.next.val == head.val) head = head.next;
if(node.next == head){
head = head.next;
node = node.next;
}else{
node.next = head.next;
head = head.next;
}
}
return dummy.next;
}
}