题目描述:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
题解:
解题思路
设立三个节点movep(用于求节点数),movept(用于处理要删除的节点),movehead(记录表头位置)
1.得到链表的节点数
2.分三种情况,节点数=1,=2,>2
3.=1则直接返回NLL,=2再分两种情况讨论(n=1,n=2),=3再分两种情况(n=节点数,n!=节点数)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
char cont = 1;
struct ListNode* movep = head;
struct ListNode* movept = head;
struct ListNode* movehead = movept;
while(movep->next){
movep = movep->next;
cont++;
}
if(cont > 2){
for(char i = 1; i < cont - n ; i++)
movept = movept->next;
if(n == cont){
movept = movept->next;
return movept;
}
movept->next = movept->next->next;
}
else if(cont == 1)
return NULL;
else {
if(n == 1) movept->next = NULL ;
else if(n == 2) {
movept = head->next;
return movept;
}
}
return movehead;
}
题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/