c语言编写的带头节点的增删改查
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
LNode * List_HeadInsert(int n){
LNode *head,*s;
int a;
head = (LNode *)malloc(sizeof(LNode));
if(head == NULL){
printf("建立失败\n");
return 0;
}
head->next = NULL;
for(int i=0;i<n;i++){
scanf("%d",&a);
s = (LNode *)malloc(sizeof(LNode));
if(head == NULL){
printf("新建节点失败\n");
return 0;
}
s->next = head->next;
s->data=a;
head->next = s;
}
return head;
}
LNode * create(int n){
LNode *head,*p,*s;
int a;
head = (LNode *)malloc(sizeof(LNode));
head->next = NULL;
p = head;
if (head == NULL) {
printf("建立失败\n");
return 0;
}
printf("请输入%d个数字\n",n);
for(int i=0;i<n;i++){
scanf("%d",&a);
s = (LNode *)malloc(sizeof(LNode));
if(s == NULL){
printf("节点建立失败");
return 0;
}
s->data = a;
s->next = NULL;
p->next = s;
p = p->next;
}
return head;
}
LNode * InsertList(LNode *L,int n,int elem)
{LNode *p,*s;
p=L;
for(int i=1;i<n;i++){
if(p == NULL){
printf("插入位置错误");
return p;
}
p=p->next;
}
s=(LNode *)malloc(sizeof(LNode));
if(s == NULL){
printf("节点建立失败");
return 0;
}
s->data = elem;
s->next = p->next;
p->next = s;
printf("在第%d位置插入数据%d成功\n",n,elem);
return L;
}
LNode * DeletList(LNode *L,int n){
LNode *p,*s;
p=L;
for (int i=1; i<n; i++) {
if (p == NULL) {
printf("删除位置节点错误");
return L;
}
p=p->next;
}
s = p->next;
p->next = p->next->next;
free(s);
printf("删除第%d位的数据成功\n",n);
return L;
}
LNode * ChangeList(LNode *L,int n,int elem){
LNode *p;
p=L;
for(int i=1;i<n;i++){
if(p == NULL){
printf("更改位置错误");
return p;
}
p = p->next;
}
p->next->data = elem;
printf("将第%d位的节点的数据更改为%d成功\n",n,elem);
return L;
}
LNode * SearchList1(LNode *L,int n){
LNode *p;
p=L;
for(int i=1;i<n;i++){
if(p == NULL){
printf("查找位置错误");
return p;
}
p = p->next;
}
printf("第%d位的数据为%d\n",n,p->next->data);
return L;
}
void SearchList2(LNode *L,int elem){
LNode *p;
p=L;
int i = 0;
while(p->next){
i++;
p = p->next;
if (p->data == elem) {
break;
}
}
printf("数值%d在此链表中的位置为:%d\n",elem,i);
}
void display(LNode *L) {
LNode *temp = L;
temp = L;
printf("此链表的存储数据为\n");
while (temp->next) {
temp = temp->next;
printf("%d", temp->data);
}
printf("\n");
}
int main(){
LNode *L,*G;
int a,b,c;
printf("请输入头插法初始链表的个数:");
scanf("%d",&a);
G = List_HeadInsert(a);
display(G);
printf("请输入尾插法初始链表的个数:");
scanf("%d",&b);
L = create(b);
display(L);
L = InsertList(L, 2, 4);
display(L);
L = DeletList(L, 3);
display(L);
L = ChangeList(L, 4, 8);
display(L);
L = SearchList1(L, 4);
SearchList2(L, 8);
}