[LeetCode] 19. Remove Nth Node From End of List

题:https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/

题目

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

题目大意

去除 有序链表 中的重复值

思路

方法一

对与当前 node,找下个 与node 不用的结点,将当前node指向下个 node。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode lp = head;
        while(lp!=null){
            
            ListNode p  = lp.next;
            
            while(p!=null && lp.val == p.val)
                p = p.next;
            lp.next = p;
            lp = lp.next;
        }
        return head;
    }
}

方法二

若下个node 与当前node不同,向下遍历;否则 提出下个node。

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

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83377602