Remove Duplicates from Sorted List

 

題目:

 

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

思路:

用兩個指針p和q,開始時q處在p的後一位,當p的值和q的值相等時,q往後移,不等時p.next = q,然後把p指向q,q再往後移一位,重複前面的過程,q等於null時結束,具體代碼如下:

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode p = head,q = head;
        while(q != null) {
            q = q.next;//放在這裏沒放在下面是爲了防止當q爲null時空指針異常
            while(q != null && p.val == q.val) {
                q = q.next;
            }
            p.next = q;
            p = q;
        }
        return head;
    }
}

 

也可以只用一個指針,代碼如下(Python實現):

 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        t = head
        while t != None:
            while t.next != None and t.val == t.next.val:
                t.next = t.next.next
            t = t.next # 這時t和t.next指向同一個元素
            if t != None:
                t.next = t.next
        return head

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章