码疯窝

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.

算法分析: 去除链表中的重复元素, 我的做法是把链表的节点值插入 hashset , 然后再去判断此节点的值是否已存在.

Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        HashSet map = new HashSet();

        ListNode tmp = head;
        ListNode next = null;
        map.add(head.val);
        while (tmp != null) {
            next = tmp.next;
            if (next == null)
                break;
            if (map.contains(next.val)) {
                tmp.next = next.next;
            } else {
                map.add(next.val);
                tmp = tmp.next;
            }
        }

        return head;
    }
}

C++:

 

Python:

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

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def deleteDuplicates(self, head):
        if (head == None or head.next == None):
            return head
        
        tmp = head
        next = None
        keys = [tmp.val]
        while(tmp != None):
            next = tmp.next
            if (next == None):
                break
            if (next.val in keys):
                tmp.next = next.next
            else:
                keys.append(next.val)
                tmp = tmp.next
        return head
继续查看有关 日志连载的文章

0个访客评论