leetcode [Remove Duplicates from Sorted List]

/**
 * 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;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值