2021.1.4 C语言 链表相关
目标:实现链表的插入与删除
法一
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
int num;
struct _node * next;//定义结构体
}node;
node * createlist(void);//插入函数
void display(node * head);//展示函数
node * Delete(node * head, int x);//删除函数
int main(void)//主函数
{
node *head;
head = createlist();
display(head);
head = Delete(head, 0);
display(head);
return 0;
}
node * createlist(void)
{
node * head = NULL, *p, *tail = NULL;
int n;
while(scanf("%d", &n) == 1)//当输入不为整数时结束
{
p = (node *)malloc(sizeof(node));
if(head == NULL)
head = p;
else
tail->next = p;
p->num = n;
p->next = NULL;
tail = p;
}
return head;
}
void display(node * head)
{
node * p;
p = head;
while(p != NULL)
{
printf("%d ",p->num);
p = p->next;
}
printf("\n");
}
node * Delete(node * head, int x)
{
if(head == NULL)
{
printf("链表为空");
return NULL;
}
node * p, * q;
p = head;
q = p->next;
while(q != NULL)
{
if(q->num == x)
{
p->next = q->next;
free(q);
q = p->next;
}
else
{
p = p->next;
q = q->next;
}
}
if(head != NULL && head->num == x)
{
q = head;
head = q->next;
free(q);
return head;
}
return head;
}
答案:
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
int main(void){
struct node *head=NULL,*last,*q,*x,*y;
int num,m;
do{
scanf("%d,&num");
if(num!=-1){
struct node *p=(struct node*)malloc(sizeof(struct node));
(*p).num =num;
(*p).next =NULL;
if(head==NULL) head=p;
else (*last).next =p;
last=p;
}
}while (num!=-1);
scanf("%d",&m);
while (head!=NULL&&(*head).num==m){
y=head;
head=(*head).next ;
free(y);
}
if(head==NULL)
printf("找不到!");
x=head;
y=head->next ;
while(y!=NULL){
if((*y).num ==m) {
(*x).next =(*y).next ;
free(y);
}
else x=y;
y=(*x).next ;
}
for (q=head;q!=NULL;q=(*q).next )
printf("%d",(*q).num );
return 0;
}