美文网首页
lintcode 112 删除链表中重复元素,留下一个

lintcode 112 删除链表中重复元素,留下一个

作者: jose_dl | 来源:发表于2017-08-04 01:34 被阅读0次
  • 思路
    要考虑到有可能重复的元素有很多个,因此下面代码不正确
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list
     * @return: ListNode head of linked list
     */
    public static ListNode deleteDuplicates(ListNode head) { 
        // write your code here
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        
        ListNode p = head;
        while(p.next!=null){
            if(p.next.val==p.val){
                p.next=p.next.next;
            }
                p=p.next;
        }
        return head;
    }  
}
这样的话,无论怎样都只是比较一次,然后p就往后移动了。如果出现这样情况比如13-13-13-13-13-13-14-15
13-13-13-13-14。。。只会删除中间的
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list
     * @return: ListNode head of linked list
     */
    public static ListNode deleteDuplicates(ListNode head) { 
        // write your code here
        if(head==null){
            return null;
        }
        if(head.next==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;
    }  
}
正确的做法就是一直比较,一直比。直到最开始的那个元素后面都没有重复的了才可以

相关文章

网友评论

      本文标题:lintcode 112 删除链表中重复元素,留下一个

      本文链接:https://www.haomeiwen.com/subject/megmlxtx.html