用c语言编程2.给你一个链表,删除链表的第 n 个结点,并且返回链表的头结点。 输入:head = [1,2,3,4,5], n = 2 输出:[1,3,4,5] 示例 2: 输入:head = [1], n = 1 输出:[] 示例 3: 输入:head = [1,2], n = 1 输出:[2] 提示: 链表中结点的数目为 sz 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz
时间: 2024-03-14 08:44:01 浏览: 56
好的,这是一个比较典型的链表问题。我给你提供一份C语言代码,可以实现这个功能:
```c
#include<stdio.h>
#include<stdlib.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
if(head == NULL || n == 0){
return head;
}
struct ListNode* p = head;
struct ListNode* q = head;
for(int i = 0; i < n; i++){
q = q->next;
}
if(q == NULL){
return head->next;
}
while(q->next != NULL){
p = p->next;
q = q->next;
}
p->next = p->next->next;
return head;
}
int main(){
// 创建链表 [1,2,3,4,5]
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->val = 3;
head->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->next->val = 4;
head->next->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->next->next->val = 5;
head->next->next->next->next->next = NULL;
// 删除第2个结点
head = removeNthFromEnd(head, 2);
// 遍历链表
struct ListNode* p = head;
while(p != NULL){
printf("%d -> ", p->val);
p = p->next;
}
printf("NULL\n");
return 0;
}
```
这个函数的实现思路是先让一个指针 `q` 往前走 `n` 步,然后再让另一个指针 `p` 和 `q` 一起往前走,直到 `q` 到达链表末尾。这时 `p` 指向的就是要删除结点的前一个结点,我们只需要修改一下指针即可。如果要删除的是头结点,我们直接返回 `head->next` 即可。
阅读全文