Remove Nth Node From End of List leetcode java


題目:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

 

題解:

 這道題也是經典題,利用的是faster和slower雙指針來解決。

首先先讓faster從起始點往后跑n步。

然后再讓slower和faster一起跑,直到faster==null時候,slower所指向的node就是需要刪除的節點。

注意,一般鏈表刪除節點時候,需要維護一個prev指針,指向需要刪除節點的上一個節點。

為了方便起見,當讓slower和faster同時一起跑時,就不讓 faster跑到null了,讓他停在上一步,faster.next==null時候,這樣slower就正好指向要刪除節點的上一個節點,充當了prev指針。這樣一來,就很容易做刪除操作了。

slower.next = slower.next.next(類似於prev.next = prev.next.next)。

同時,這里還要注意對刪除頭結點的單獨處理,要刪除頭結點時,沒辦法幫他維護prev節點,所以當發現要刪除的是頭結點時,直接讓head = head.next並returnhead就夠了。

 

代碼如下:

 1     public  static ListNode removeNthFromEnd(ListNode head,  int n) {
 2          if(head ==  null || head.next ==  null)
 3              return  null;
 4             
 5         ListNode faster = head;
 6         ListNode slower = head;
 7         
 8          for( int i = 0; i<n; i++)
 9             faster = faster.next;
10             
11          if(faster ==  null){
12             head = head.next;
13              return head;
14         }
15         
16          while(faster.next !=  null){
17             slower = slower.next;
18             faster = faster.next;
19         }
20         
21         slower.next = slower.next.next;
22          return head;
23         
24         }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM