單向鏈表的增刪改查(C語言版)
#include <stdio.h>
#include <stdlib.h>
struct Stu create(int n);
void print(struct Stu head);
void deleteNode(struct Stu head,int n);
void insertNode(struct Stu head,int n);
void change(struct Stu head,int n);
struct Stu{
int id;
char name[50];
struct Stu next;
};
int main(){
int n,j,in,cn;
char c;
struct Stu head = NULL; //建立頭指針
printf("請輸入你想要建立的節點個數:\n");
scanf("%d",&n);
head = create(n);
print(head);
while(true){
printf("請選擇你想要執行的操做:\n");
printf("1.插入節點\n2.刪除節點\n3.修改節點\n4.退出程序\n");
scanf(" %c",&c);
if(c =='1'){
printf("你想要在哪插入節點:\n");
scanf("%d",&in);
insertNode(head,in);
print(head);
}else if(c == '2'){
printf("你想要刪除哪一個節點的數據:\n");
scanf("%d",&j);
deleteNode(head,j);
print(head);
}else if(c =='3'){
printf("你想要修改哪一個節點的數據:\n");
scanf("%d",&cn);
change(head,cn);
print(head);
}else if(c =='4'){
exit(0);
}
}
}
struct Stu create(int n){
struct Stu head,node,end; //定義頭節點,普通節點,尾節點
head = (struct Stu )malloc(sizeof(struct Stu)); //給頭節點申請內存
//head->id = n; //頭節點的數據域保存鏈表的長度
end = head; //如果空表,則頭尾地址一致
for(int i=0;i<n;i++){ //利用for循環向鏈表中添加數據
node = (struct Stu )malloc(sizeof(struct Stu));//給普通節點申請內存空間
scanf("%d %s",&node->id,node->name); //給數據域賦值
end->next = node; //讓上一個節點的數據域指向當前節點
end = node; //end指向當前節點,最終end指向尾節點
}
end->next = NULL; //給end的指針域置空
return head; //返回頭節點的地址
}
void print(struct Stu head){
struct Stu p = head;
int j =1;
p = p->next; //不打印頭節點的數據域中的值
while(p != NULL){
printf("%d\t%d\t%s\n",j,p->id,p->name);
p = p->next;
j++;
}
}
void deleteNode(struct Stu head,int n){ //刪除n處的節點
struct Stu p = head,pr = head;
int i =0;
while(i<n&&p!=NULL){ //到達指定節點,此時p指向指定節點,pr指向上一節點
pr = p;
p = p->next;
i++;
}
if(p!=NULL){
pr->next = p->next;
free(p);
} else{
printf("節點不存在!\n");
}
}
void insertNode(struct Stu head,int n){ //插入節點
struct Stu p = head,pr;
pr = (struct Stu)malloc(sizeof(struct Stu)); //讓pr指向新建節點申請的內存
printf("input data:\n");
scanf("%d %s",&pr->id,pr->name);
int i = 0;
//當插入位置是尾節點時,只要在尾節點後再插入一個節點,並讓尾節點的指針域指向新建節點,新建節點的指針域置空
while(i<n&&p!=NULL){ //使p指向將要插入節點的位置
p = p->next;
i++;
}
if(p!=NULL){ //若是p沒越界
pr->next = p->next; //將新建節點的地址指向將要插入節點的後一個節點的地址
p->next = pr; //使插入節點指向新建節點
}else{
printf("節點不存在!\n");
}
}
void change(struct Stu head,int n){
struct Stu p = head;
int i = 0;
while(i<n && p!=NULL){ //使p指向需修改節點
p = p->next;
i++;
}
if(p != NULL){
printf("請輸入修改以後的值:\n");
scanf("%d %s",&p->id,p->name);
}else{
printf("節點不存在!\n");
}
} node