删除重复节点

来源:互联网 发布:淘宝知识产权投诉撤销 编辑:程序博客网 时间:2024/06/09 20: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.

Subscribe to see which companies asked this question

思路:后面的与当前的相同删除后面的即可,但是这种方法只能删除连续重复的(即1,1,1这种1,2,1这种无法删除)

代码:

import java.util.ArrayList;/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        ListNode node = head;        for(;node!=null;node=node.next){            while(node.next!=null&&node.val==node.next.val){                if(node.next==null)node=null;                node.next = node.next.next;            }        }        return head;    }}
递归的(有木有很赞啊!!虽然不是我写的(* ——*))

public ListNode deleteDuplicates(ListNode head) {        if(head == null || head.next == null)return head;        head.next = deleteDuplicates(head.next);        return head.val == head.next.val ? head.next : head;}
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        ListNode pre = new ListNode(-1);//to avoid the head check        pre.next = head;        ListNode cur = pre;        //ListNode node = head;        while(cur.next!=null){            if(cur.next.val==cur.val)cur.next = cur.next.next;            else                cur = cur.next;        }        return head;    }}



0 0
原创粉丝点击