83.Remove Duplicates from Sorted List - easy

 

 

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

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        ans = []
        res = ListNode(0)
        res_s = res
        if not head:
            return None
        while head:
            if head.val not in ans:
                ans.append(head.val)
            head = head.next
        for i in range(len(ans)):
            tmp = ListNode(ans[i])
            res.next = tmp
            res = res.next
        return res_s.next

 

 

 

Java 版:

  • 遍历一遍链表,将不相等的加入到结果链表中,如果相等就跳过。

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return null;
        ListNode res = head, tmp = head;
        head = head.next;
        while(head != null){
            if(head.val != tmp.val){ //不相等时,加入结果集中
                tmp.next = head;
                tmp = tmp.next;
            }
            head = head.next;
        }
        tmp.next = null; //后续节点置 null
        return res;
    }
}

 

posted @ 2020-05-09 15:08  星海寻梦233  阅读(75)  评论(0编辑  收藏  举报