链表节点的删除

师–链表的结点插入
Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
给出一个只有头指针的链表和 n 次操作,每次操作为在链表的第 m 个元素后面插入一个新元素x。若m 大于链表的元素总数则将x放在链表的最后。

Input
多组输入。每组数据首先输入一个整数n(n∈[1,100]),代表有n次操作。

接下来的n行,每行有两个整数Mi(Mi∈[0,10000]),Xi。

Output
对于每组数据。从前到后输出链表的所有元素,两个元素之间用空格隔开。

Sample Input
4
1 1
1 2
0 3
100 4
Sample Output
3 1 2 4
Hint
样例中第一次操作1 1,由于此时链表中没有元素,1>0,所以此时将第一个数据插入到链表的最后,也就是头指针的后面。

Source
在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
struct st
{
int date;
struct st *next;
};
int main()
{
int n,m,x;
struct st *head,p,q;
while(scanf("%d",&n)!=EOF)
{
head=(struct st
)malloc(sizeof(struct st));
head->next=NULL;
while(n–)
{
scanf("%d%d",&m,&x);
p=head;
while(m–&&p->next!=NULL)
{
p=p->next;
}
q=(struct st
)malloc(sizeof(struct st));
q->date=x;
q->next=p->next;
p->next=q;
}
for(p=head->next;p!=NULL;p=p->next)
{
if(p->next==NULL)
printf("%d\n",p->date);
else
printf("%d ",p->date);
}
}
return 0;
}

在C语言中,链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据部分和指向下一个节点的指针。链表节点删除和插入操作是基本操作之一,需要仔细处理指针以保证数据的连续性和正确性。 节点删除操作通常包含以下步骤: 1. 遍历链表,定位到要删除节点的前一个节点。 2. 修改前一个节点的next指针,使其指向当前节点的下一个节点。 3. 释放当前节点所占用的内存资源。 节点插入操作通常包含以下步骤: 1. 定位到要插入位置的前一个节点。 2. 创建一个新的节点,并将数据复制到这个节点中。 3. 修改新节点的next指针,使其指向原来前一个节点的下一个节点。 4. 修改前一个节点的next指针,使其指向新创建的节点。 下面是一个简单的示例代码,展示了在单向链表删除和插入节点的基本操作。 ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node *next; } Node; // 创建新节点 Node* createNode(int data) { Node *newNode = (Node*)malloc(sizeof(Node)); if (!newNode) { printf("内存分配失败\n"); exit(1); } newNode->data = data; newNode->next = NULL; return newNode; } // 在链表尾部插入节点 void insertNode(Node **head, int data) { Node *newNode = createNode(data); if (*head == NULL) { *head = newNode; } else { Node *current = *head; while (current->next != NULL) { current = current->next; } current->next = newNode; } } // 删除链表中的节点 void deleteNode(Node **head, int data) { if (*head == NULL) return; Node *current = *head; Node *previous = NULL; if (current->data == data) { *head = current->next; free(current); return; } while (current != NULL && current->data != data) { previous = current; current = current->next; } if (current == NULL) return; previous->next = current->next; free(current); } // 打印链表 void printList(Node *node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n"); } int main() { Node *head = NULL; // 插入节点 insertNode(&head, 1); insertNode(&head, 2); insertNode(&head, 3); printf("原始链表: "); printList(head); // 删除节点 deleteNode(&head, 2); printf("删除节点2后的链表: "); printList(head); // 清理链表内存 while (head != NULL) { Node *temp = head; head = head->next; free(temp); } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值