/**
* 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)
return null;
ListNode res = new ListNode(head.val);
ListNode shift = res;//用shift来代替res做移动,因为最后返回的是res
int tempVal = head.val;//用tempVal来装最近装入res链表中的值
head = head.next;
while(head != null){
if(head.val != tempVal){//head中与上一次不重复的才装入那个链表中
shift.next = new ListNode(head.val);
tempVal = head.val;
head = head.next;
shift = shift.next;
}
else{
head = head.next;//相同时不插入res,但head也要移动
}
}
return res;
}
}
解法二:
/**
* 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 shift = head;//用shift来代替head移动
if(shift == null)
return null;
//解法一新建了一个结果链表,现在采用直接在head上修改的方式,题目中提到了链表是有序的
while(shift.next != null){//while(shift != null)不行,因为涉及到了shift.next.val
if(shift.val == shift.next.val){//判断前后两个数是否相等,相等就移向后一个
shift.next = shift.next.next;//若相等shift不要往后移(下一行注释部分不要执行),接着判断前一个与后移的一个数是否相等
//shift = shift.next;
}
else{
shift = shift.next;//不相等时shift要往后找啊,此时链表本身没有修改
}
}
return 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) {//解法三:分治法
if(head == null || head.next == null)//递归出口
return head;
//分,递归调用,分成【head这个单独结点】与【head.next之后的链表】两部分
head.next = deleteDuplicates(head.next);
//治,判断head.val与head.next.val是否相等来决定返回head还是head.next,因为只有两部分(其中一部分还只是一个结点)就显得直观了
return head.val == head.next.val ? head.next : head;
}
}