第一题是吧1-1-2-3-3-4变成1-2-3-4,第二题是把它变成2-4。
第一题从开头节点开始,如果下一个节点和它一样就删除,如果不一样就前进一位。
第二题需要在链表前面补一个节点,用head.next作开头进行判断,同时用tmp引用找出相同节点段的末尾一次全删掉。
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return head;
ListNode start=head;
while(head.next!=null){
if(head.next.val==head.val){
if(head.next.next==null) {
head.next=null;
break;
}
else head.next = head.next.next;
}else
head=head.next;
}
return start;
}
第二题:
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return null;
ListNode h = new ListNode(0);
h.next=head;
head=h;
while(h.next.next!=null){
ListNode tmp=h.next.next;
if(h.next.val!=tmp.val){
h=h.next;
continue;
}
while(h.next.val==tmp.val){
tmp=tmp.next;
if(tmp==null){
h.next=null;
return head.next;
}
}
h.next=tmp;
if(h.next==null)break;
}
return head.next;
}
Update 2015/07/26:
1.
/**
* 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;
ListNode start = head;
while (head.next != null){
if (head.next.val != head.val){
head = head.next;
}else{
ListNode p = head.next;
while(p != null && p.val == head.val){
p=p.next;
}
if (p == null){
head.next = null;
return start;
}else{
head.next = p;
head = p;
}
}
}
return start;
}
}
2.
/**
* 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;
ListNode start = head;
while (head.next != null){
if (head.next.val != head.val){
head = head.next;
}else{
ListNode p = head.next;
while(p != null && p.val == head.val){
p=p.next;
}
if (p == null){
head.next = null;
return start;
}else{
head.next = p;
head = p;
}
}
}
return start;
}
}