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;
* next = null;
* }
* }
*/
//思想同昨天的从有序数组去重复元素是一样的
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head==null || head.next==null) return head;
ListNode pre = head;
ListNode cur = head.next; //cur与pre用来在list中找重复
ListNode non_dup_end = head; //用来标记无重复list的最后一个节点
while(cur != null){
if (pre.val != cur.val){ //如果不是重复的话,属正常态,就把non_dup_end向后移一位,然后把cur.val赋过去
non_dup_end = non_dup_end.next;
non_dup_end.val = cur.val;
}
cur = cur.next; //如果是重复的话,本次循环什么都不做,直到找到后边第一个不再重复的元素值赋给non_dup_end
pre = pre.next;
}
non_dup_end.next = null; //不同于数组,循环之后要记得把无重复list后边多余的节点删掉
return head;
}
}