LeetCode:Remove Nth Node From End of List

       

问题不是太难,但是得注意,移除的第n个结点是从链表结尾算起。

算法思路:

1)首先判断链表head是否为空,或者n是否大于0;

2)统计链表长度length,将从尾部算起待移除的第n个结点转化为从链表首部开始的第target个结点;

     (taget=ListLength+1-n)

3)  判断是否删除的是头结点;

4)对链表进行遍历,找到第target结点进行删除;

     (添加变量before_head,用于存放当前结点的前个结点地址)


给出算法源码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    
    int ListLength;
    int count=0;
    int target;
    struct ListNode *c_head=head;
    struct ListNode *before_head;
    
    if(n<0 || head==NULL)
    {
        
        printf("something wrong in call\n");
        exit(-1);
    }
    
    //calculate the list length
    for( ; c_head!=NULL; c_head=c_head->next)
    {
        count++;
    }
    ListLength=count;
    c_head=head;
    
    target=ListLength+1-n;
    
    if(target==1)//delete the head
    {
        
        head=head->next;
        free(c_head);
        return head;
    }
    
    for(count=0,before_head=c_head; c_head!=NULL; c_head=c_head->next )
    {
        
        count++;
        if(count==target)
        {
            before_head->next=c_head->next;
            free(c_head);
            return head;
        }
        
        if(count==1)
        {
            before_head=before_head;
        }
        else
        {
            before_head=before_head->next;
        }
    }
    
    if(count==ListLength)
    {
        printf("not found that node\n");
        exit(-1);
    }
    
    
    
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值