注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
题目在这里82. Remove Duplicates from Sorted List II我觉得这个和string去重思路是一样的,重复的一个也不留,这个是string的写法:
- public String deDup(String input) {
- //corner case
- if(input==null || input.length()<=1) return input;
- char[] array = input.toCharArray();
- int end=0; //the top of stack
- for(int i=1;i<array.length;i++){
- if(end == -1 || array[i]!=array[end]){
- array[++end] = array[i]; //日常拷贝
- }else{
- end--;
- while(i+1<array.length && array[i]==array[i+1]){
- i++;
- }
- }
- }
- return new String(array,0,end+1);
- }
复制代码
所以我觉得相同的思路,这个链表也能写,所以就有了:
- public ListNode deleteDuplicates(ListNode head) {
- if(head == null) return head;
- ListNode slow = head;
- ListNode fast = head;
- //here should be dummy head
- ListNode dummy = new ListNode(-1);
- dummy.next = head;
- // here should have dummy && pre node of slow
- ListNode prev = head;
-
- while(fast!= null){
- if(slow.val != fast.val){
- prev.val = slow.val;
- slow = slow.next;
- slow.val = fast.val;
- }else{
-
- slow = prev; //死循环,而且还不能任意改动.val值
- while(fast.next!=null && slow.val == fast.val){
- fast = fast.next;
- }
- }
- }
- //断点
- slow.next = null;
- return dummy.next;
- }
复制代码
可是我发现,换成链表了要不就是slow!=null || 不能加,要么就会陷入死循环
不知道该如何处理prev(对应end--)这个操作
在list中引入prev,这样写会在出现NPE
- if(slow!=null|| slow.val != fast.val){
- prev = slow;
- slow = slow.next;
- slow.val = fast.val; //here
复制代码
然后这样改动还会死循环:
- }else{
- slow = prev; //死循环,因为slow永远=prev
- while(fast.next!=null && fast.val == fast.next.val){
- fast = fast.next;
- }
复制代码
想了一天,问了一天了,实在没办法po在地里了,希望大佬们指点迷津
就是按照string那个思路来走,对应着链表中,应该怎么改呢
|