Leecode Remove Duplicates from Sorted List

来源:互联网 发布:淘宝默认好评是几天 编辑:程序博客网 时间:2024/06/10 04:19


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.

 

class Node{private int val; Node next;public Node(int val) {this.val = val;this.next = null;}}
public Node removeduplicate(Node head){Node p = head ;Node cur = head ;while(p.next!=null){if(p.next.val!=p.val){cur.next = p.next;cur = p.next;}p = p.next;}cur.next =  p.next;        return head;}


我们把相邻两数不相等的地方称为边界,再用cur指针指向边界的开始处,当p指针在前进的过程中遇到下一个边界时去掉中间部分

下面的方法更好,

 

public class Solution {    public ListNode deleteDuplicates(Node head) {        if(head == null || head.next == null)            return head;         Node p = head;         while( p!= null && p.next != null){            if(p.val == p.next.val){                p.next = p.next.next;            }else{                p = p.next;             }        }         return head;    }} 


 

每次前进时发现相同则去掉一个继续前进,若不同则继续前进。感觉比较直观简单。
0 0