LeetCode 02.01 移除重复节点

移除重复节点

要求:

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

示例:

输入:[1, 2, 3, 3, 2, 1]

输出:[1, 2, 3]

代码实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        ListNode temp = head;
        ListNode top;
        while(temp!=null){
            top = temp;
            while(top.next!=null){
                if(temp.val == top.next.val){
                top.next = top.next.next;
                }else{
                    top = top.next;
                }  
            }
            temp = temp.next;
        }
        return head;
    }
}

你可能感兴趣的:(Java算法)