[leetcode-]Remove Nth Node From End of List(C)

来源:互联网 发布:java 模块化开发 编辑:程序博客网 时间:2024/06/06 03:10

问题描述:
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的长度呢?一个显然的办法是维护两个指针,这两个指针间相距n,然后当最后一个指针到达null时,此时,第一个指针就是要删除的元素。

代码如下:0ms

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {    struct ListNode *prev=head,*next = head;    int i;    if(n<=0)        return head;    for(i = 0;i<n;i++){        next = next->next;    }    if(next==NULL)//到达最后        return head->next;    while(next->next!=NULL){        prev = prev->next;        next = next->next;    }    prev->next = prev->next->next;    return head;}
0 0
原创粉丝点击