Remove Duplicates from Sorted List 从链表里移除重复元素 @LeetCode

来源:互联网 发布:nba2k16mc生涯数据 编辑:程序博客网 时间:2024/06/03 08:35

题目:

在已排序好的链表中,移除重复元素


思路:

用两个指针,一个base指向被比较的对象,另一个cur指向当前比较的对象。

如果cur指向的元素和base指向元素相同,则跳过重复元素,不更新base。

如果。。。。。。。。。。。。。。不同,则更新base。

cur一直都在更新。


package Level1;import Utility.ListNode;/** * 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. */public class S83 {public static void main(String[] args) {ListNode n1 = new ListNode(1);ListNode n2 = new ListNode(1);n1.next = n2;ListNode n3 = new ListNode(2);n2.next = n3;ListNode x = deleteDuplicates(n1);x.print();}public static ListNode deleteDuplicates(ListNode head) {ListNode base = head;  // base 为每次被比较的对象if(head==null || head.next == null){return head;}ListNode cur = head.next;// cur为每次去比较的对象        while(base!=null && cur!=null){        if(base.val == cur.val){// 重复了就跳过去        base.next = cur.next;        }else{// 不重复就更新base        base = base.next;        }        cur = cur.next;// 更新cur        }                return head;    }}


/** * 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;        }        ListNode p = head, q = head;        while(q != null){            if(q.val == p.val){                q = q.next;            }else{                p.next = q;                p = q;            }        }        p.next = q;     // Take care of last element! eg 1,1        return head;    }}




原创粉丝点击