FTPrep, 83 Remove Duplicates from Sorted List

来源:互联网 发布:淘宝达人怎么收费 编辑:程序博客网 时间:2024/06/03 22:53

值得总结的就是:与array相比,要修改(在list中是断开链接操作)一个值,没有index所以不具备array的功能。

所以只能通过node的前续节点来access/getter 并且比较,然后再做断开修改的方式.

一般只要断开的,都是通过前继节点,比如说remove the last k-th node的那道题。TODO,值得总结,list的各种处理方式

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head==null) return head;        ListNode dummy = new ListNode(-1);        dummy.next=head;        ListNode checkValidForNext=dummy;        ListNode scanCurrAndCompareNext=head;        while(scanCurrAndCompareNext!=null){            while(scanCurrAndCompareNext.next!=null && checkValidForNext.next.val==scanCurrAndCompareNext.next.val) {                scanCurrAndCompareNext=scanCurrAndCompareNext.next;               }            checkValidForNext.next =scanCurrAndCompareNext; // nice, directly link to the last one in any duplicate series.            checkValidForNext=checkValidForNext.next; // move 1 step so points to the valid node, and ready to check the next one            scanCurrAndCompareNext=scanCurrAndCompareNext.next; // move 1 step for scan pointer too.        }        return dummy.next;    }}// 值得总结的就是:与array相比,要修改(在list中是断开链接操作)一个值,没有index所以不具备array的功能。// 所以只能通过node的前续节点来access/getter 并且比较,然后再做断开修改的方式.// 一般只要断开的,都是通过前继节点,比如说remove the last k-th node的那道题。TODO,值得总结,list的各种处理方式




原创粉丝点击