Leetcode c语言-Remove Nth Node From End of List

Title:

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.


这道题目如果用一般的方法,非常容易,首先就是算出链表的长度,然后根据长度和n的关系进行处理,只需要当遇到要remove的节点事,将它的前一个节点 head->next=head->next->next,也就是跳过这个节点即可:


solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    int i=0;
    int len=0;

    struct ListNode* temp_head =head;
    struct ListNode* result_head =head;
        
    while(temp_head != NULL) {
        len++;    
        temp_head=temp_head->next;
    }
    
    if (len==1)
        return NULL;
    
   while(i<len-n-1){
       result_head=result_head->next;
       i++;
   }
   if ((len-n) == 0)
       head=head->next;
   else
   result_head->next=result_head->next->next;
    
   return head;
    
}


但是这种方法有两个遍历,题目要求说最好使用一个pass,那么就要想,肯定不能全部遍历完,再替换,因为这种操作是不存在的。因此要在遍历过程中,进行替换。那么如何确定要替换的节点的位置呢,这里就需要用到两个指针,第一个指针标明位置,比如第一个指针先向后移动n个,这个时候剩余的长度为len-n,这个长度正好是我们需要的,然后再用第二个指针,该指针和第一个指针同时向后移动,当第一个指针移到最后,那么第二个指针也就移到了len-n的位置,然后删掉该节点即可。

在这种操作中,要注意一点,当第一个指针移动n个后,该指针是NULL,那么就说明,n为长度len了。这种情况只需要将第一个节点删掉即可:head=head->next.


贴出代码:

solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    int i=0;
    int len=0;

    struct ListNode* temp_head =head;
    struct ListNode* result_head =head;
        
    if (!head->next) return NULL;
    
    for (i=0;i<n;i++) {
        temp_head=temp_head->next;
    }
    if (!temp_head) return head->next;
    
    while(temp_head->next) {
        temp_head = temp_head->next;
        result_head = result_head->next;
    }
    result_head->next = result_head->next->next;
        
   return head;
    
}


转载于:https://www.cnblogs.com/sichenzhao/p/9320230.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值