您的位置:首页 > 其它

leetcode--Remove Duplicates from Sorted List

2016-04-28 15:21 393 查看
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.

/**
* 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) {
if(head==null||head.next==null) return head;
ListNode curr=head;
while(curr.next!=null){
if(curr.val==curr.next.val){
curr.next=curr.next.next;
}
else{
curr=curr.next;
}
}
return head;
}
}


拓展。删除数字中的重复数字。:

package test;

import java.util.ArrayList;

public class deleteDumpleNum {

private static ArrayList deleDump(int[] a) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (a.length == 1) {
res.add(a[0]);
return res;
} else {
res.add(a[0]);
for (int i = 1; i < a.length; i++) {
if (a[i] != a[i - 1]) {
res.add(a[i]);
}
}
}
return res;

}

public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 5, 6 };
ArrayList<Integer> out = deleDump(a);
for (int i = 0; i < out.size(); i++) {
System.out.print(out.get(i) + "\t");
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: