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.
這是第一道完全在web中寫並且提交通過的題目。
跟之前的那道排序數組中消去一樣的數字是一個意思。但是用鏈表操作就容易多了。
忽略掉中間相等的直接拼接到不相等的那個元素過去就ok了。
上代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return head;
int nowValue=head.val;
ListNode nowPoint=head;
ListNode pointer=head;
for(int indexList=0;pointer!=null;pointer=pointer.next){
if(nowPoint.val==pointer.val){
nowPoint.next=pointer.next;
}else{
nowPoint=pointer;
}
}
return head;
}
}