#include <stdio.h>
#include <stdlib.h>
typedef struct LINK
{
int data;
struct LINK *next;
}link;
link *appendnode(link *head);
void displynode(link *head);
link *deletenode(link *head,int nodedata);//删除节点
void deletememory(link *head);//释放head指向的链表中的所有节点占用内存
int main()
{
int i=0,nodedata;
char c;
link *head=NULL;
printf("do you want to append a new code(Y/N)?");
scanf(" %c",&c);
while(c=='Y'||c=='y'){
head=appendnode(head);
displynode(head);
printf("do you want to append a new code(Y/N)?");
scanf(" %c",&c);
i++;
}
printf("%d new node have been appended!\n",i);
printf("what nodedata do you want to delete?\n");//删除指定节点
scanf("%d",&nodedata);
head=deletenode(head,nodedata);
displynode(head);
deletememory(head);
return 0;
}
link *appendnode(link *head){
link *p=NULL,*pr=head;
int data;
p=(link *)malloc(sizeof(link));
if(p==NULL){
printf("no enough memory to allocate!\n");
exit(0);
}
if(head==NULL){
head=p;
}else{
while(pr->next!=NULL){
pr=pr->next;
}
pr->next=p;
}
printf("input node data:");
scanf("%d",&data);
p->data=data;
p->next=NULL;
return head;
}
void displynode(link *head){
link *pr=head;
int j=1;
while(pr!=NULL){
printf("%5d%10d\n",j,pr->data);
pr=pr->next;
j++;
}
}
void deletememory(link *head){
link *p=head,*pr=head;
while(p!=NULL){
pr=p;
p=p->next;
free(pr);
}
}
//单向链表删除操作
link *deletenode(link *head,int nodedata){
link *p=head,*pr=head;
if(head==NULL){
printf("linked table is empty!");
exit(0);
}
while(pr->data!=nodedata && pr->next!=NULL){
p=pr;//p中保存当前节点的指针
pr=pr->next;//pr指向当前节点的下一节点
}
if(pr->data==nodedata){
if(pr==head){
head=pr->next;
}
else{
p->next=pr->next;
}
free(pr);
}else{
printf("this node has not been found!");
}
return head;
}
C 单向链表的建立和删除操作
最新推荐文章于 2022-06-13 00:02:13 发布