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

 

题目:

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

例如,

   给定链表:1-> 2-> 3-> 4-> 5,n = 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 }

 

转载于:https://www.cnblogs.com/xuzhiyuan/p/7651098.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值