#include<stdio.h>
#include"stdlib.h"
//Definition for singly-linked list.
typedef struct ListNode {
int val;
struct ListNode *next;
}node;
node* create(int n)//假设有n个节点
{
node* p = NULL;
node* head =NULL;
int i = 1;
while(i <= n)
{
if(!head){
head = p =(node*)malloc(sizeof(struct ListNode));
printf("p->val=\t");
scanf("%d",&p->val);//赋值
p->next = NULL;
}else{
p->next = (node*)malloc(sizeof(struct ListNode));
printf("p->val=\t");
scanf("%d",&p->next->val);//赋值
p->next->next = NULL;
p = p->next;
}
++i;
}
return head;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
int i=1, all=0;
struct ListNode* p = head;//用来计算节点个数
struct ListNode* q = head;//用来寻找并改变节点
struct ListNode* s = q; //用来保存头节点
struct ListNode* f ; //用来保存节点
while(p != NULL){//计算出节点个数
p = p->next;
++all;
}
int pos = all - n;//计算出相应位置
if(!all){
return NULL;
}
while(q != NULL){
if(i==pos){ //找到相应位置
f = q->next;// 保存
q->next = f->next;
free(f); //释放
break;
}
else if(pos==0){
s = s->next;//移动头节点
break;
}
q = q->next;
i++;
}
if(s){
return s;
}
else{
return NULL;
}
}
int main()
{
int n, m;
printf("输入创建节点个数:\t");
scanf("%d", &n);
node* p = create(n);
printf("输入需要删除倒数第几个节点:\t");
scanf("%d", &m);
node* q = removeNthFromEnd( p, m);
while(q != NULL){
printf("p->val=%5d\n", q ->val);
q = q->next;
}
}
删除链表倒数第N个节点
最新推荐文章于 2024-10-04 11:12:05 发布
该博客介绍了如何使用C语言创建一个单链表,并实现删除链表中倒数第n个节点的功能。通过定义链表结构体,利用指针操作动态分配内存来构建链表。在删除节点时,先计算链表长度,然后找到目标位置进行删除。代码清晰地展示了链表操作的基本步骤。
484

被折叠的 条评论
为什么被折叠?



