19.从列表末尾删除第N个节点(19. Remove Nth Node From End of List)

 

题目:

给定一个链表,从列表的末尾删除第节点并返回其头。

例如,

   给定链表:1-> 2-> 3-> 4-> 5n = 2

   从结尾移除第二个节点后,链表将变为1-> 2-> 3-> 5

注意:
给定n将始终有效。
尝试在一次通过这样做。

 

思路:(1)删除从尾数第n节点,即删除从头数第target=nums(链表节点总数)-n+1个节点;

(2)删除第target个节点只需找到taget-1个节点temp;然后令temp.next=temp.next.next;(注意:若target为第一个节点则直接将第二个节点作为头节点返回(即return head.next;)

(3)返回head;

 

代码:

 

 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         int nums=0;//链表结点总数
13         ListNode temp=head;
14         while(temp!=null){
15 
16             nums++;
17             temp=temp.next;
18             
19         }
20         
21         int target=nums+1-n;//从头开始数,要删除节点的位置
22         
23         if(target==1){//若要删除第一个节点,则直接返回head.next;
24             
25             return head.next;
26             
27         }
28         
29         temp=head;
30         for(int i=1;i<nums;i++){
31             
32             if(i==(target-1)){
33                 
34                 temp.next=temp.next.next;
35                 return head;
36     
37             }
38             temp=temp.next;
39             
40         }
41         
42         
43         return null;
44     }
45 }

 

posted @ 2017-10-11 16:04  xzy不会飞的地板流  阅读(245)  评论(0编辑  收藏  举报