19. Remove Nth Node From End of List

题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

 

解题思路:

倒数第几个节点的问题,和剑指offer上的不一样

这个问题:快指针先走n步,然后slow走的节点其实是倒数第n+1个节点,这样方便删除节点。

当让slower和faster同时一起跑时,就不让 faster跑到null了,让他停在上一步,faster.next==null时候,这样slower就正好指向要删除节点的上一个节点,充当了prev指针。这样一来,就很容易做删除操作了。

slower.next = slower.next.next(类似于prev.next = prev.next.next)。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         
12         //利用slow和faster来解决
13         
14         //定义两个指针,快指针先走n步,然后慢指针走,当快指针走到最后时,慢指针也就到了倒数第n个位置.
15         
16         if(head==null || n==0)
17             return null;
18         
19         ListNode slow=head;
20         ListNode fast=head;
21         
22         // if(fast ==null)
23         // {
24         //     head=head.next;
25         //     return head;
26         // }
27         for(int i=0;i<n;i++)
28         {
29             if(fast.next!=null)
30                 fast = fast.next;
31             else
32             {
33                 head = head.next;
34                 return head;
35             }
36                 
37         } 
38         while(fast.next!=null)
39         {
40             slow = slow.next;
41             fast = fast.next;
42             
43         }
44         slow.next = slow.next.next;
45         return head;
46     }
47 }

 

剑指offer题目

解题思路:

走K-1步,千万注意!!!

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode FindKthToTail(ListNode head,int k) {
12         
13         if(head==null||k<=0)
14         {
15             return null;
16         }
17         
18         ListNode fast=head;
19         ListNode slow=head;
20         
21         for(int i=1;i<k;i++)
22         {
23             if(fast.next!=null)
24             {
25                 fast=fast.next;
26             }
27             else
28             {
29                 return null;
30             }
31         }
32         
33         while(fast.next!=null)
34         {
35             fast=fast.next;
36             slow=slow.next;
37         }
38         return slow;
39 
40     }
41 }

 

posted @ 2019-05-07 21:57  王爷爱吃秋刀鱼  阅读(133)  评论(0编辑  收藏  举报