点击 这里 跳转到LeetCode官网查看题目
点击 这里 跳转到LeetCode中国官网查看题目
- Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
中文:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
Accept by C:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
//设置工作指针指向头节点
struct ListNode* p = head;
//获得链表长度
int count = 0;
while(p != NULL){
++count;
p = p -> next;
}
//获取第length - n个节点的地址
p = head;
int i = 1;
while(i++ < count - n){
p = p -> next;
}
//如果要删除的是头节点
if(count == n){
struct ListNode* s = head;
head = head -> next;
free(s); //释放
return head;
}
//其余情况
struct ListNode* p1 = p -> next;
p -> next = p -> next ->next;
free(p1);//释放
return head;
}
![](https://img.haomeiwen.com/i16314622/bc247b201998644b.png)
网友评论