c语言编写的带头节点的增删改查
// 带头节点的链表的增删改差
#include
#include
#include
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;inext = head->next;
s->data=a;
head->next = s;
}
return head;
}
LNode * create(int n){//尾插法创建一个有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;idata = a;
s->next = NULL;
p->next = s;
p = p->next;
}
return head;
}
LNode * InsertList(LNode *L,int n,int elem)//在第n个位置插入元素elem
{LNode *p,*s;
p=L;
for(int i=1;inext;
}
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){//删掉第i个数据
LNode *p,*s;
p=L;
for (int i=1; inext;
}
s = p->next;
p->next = p->next->next;
free(s);
printf("删除第%d位的数据成功n",n);
return L;
}
LNode * ChangeList(LNode *L,int n,int elem){ //将第n位的数据更改为elem
LNode *p;
p=L;
for(int i=1;inext;
}
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;inext;
}
printf("第%d位的数据为%dn",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在此链表中的位置为:%dn",elem,i);
//return i;
}
void display(LNode *L) {//遍历输出链表
LNode *temp = L; //创建一个临时结点用来遍历
temp = L;
//只要temp->next不指向NULL就输出
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);
}