19. Remove Nth Node From End of List

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 
10 class Solution 
11 {
12 public:
13     ListNode* removeNthFromEnd(ListNode* head, int n) 
14     {
15         ListNode *pre=head,*beh=head; //after operation,pre is the previous node of which node we want to delete
16         int count=1;
17         while(count<=n)        //fixed the distance between pre and beh
18         {
19             beh=beh->next;
20             count++;
21         }
22         if(beh==NULL)         //if n is equal to the length of linklist,delete first node
23             return head->next;
24         while(beh->next!=NULL)  //when beh reach to the last node,pre is the previous node of n(th) node from end of list
25         {
26             pre=pre->next;
27             beh=beh->next;
28         }
29         beh=pre->next;   
30         pre->next=pre->next->next;  //delete pre->next 
31         free(beh);   
32         return head;
33     }
34 };

用两个指针,指针之间相距n,当快指针跑到链表末尾时,慢指针正好指向倒数第n个节点的前一个节点,删除pre的下一个节点即可

转载于:https://www.cnblogs.com/zhuangbijingdeboke/p/9272553.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值