您的位置:首页 > 编程语言 > Java开发

删除重复节点

2016-01-05 22:41 597 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 链表 算法