#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
#define NEW (struct node *)malloc(sizeof(struct node)) //开辟新结点
int main()
{
struct node *buildnode();
void printnode(struct node *head);
struct node *delnode(struct node *head, int N);
struct node *insertnode(struct node *head, int N);
struct node *p;
int n;
p = buildnode();
printf("输出\n");
printnode(p);
printf("请输入要删除的结点\n");
scanf("%d",&n);
p = delnode(p,n);
printnode(p);
printf("请输入指定的结点,在指定结点前插入新的结点\n");
scanf("%d",&n);
p = insertnode(p,n);
printnode(p);
return 0;
}
struct node *buildnode() //建立一个单链表
{
struct node *head,*p,*q;
int i,tmp;
head = NEW;
head->next = NULL;
q = head;
printf("请输入9个整数\n");
for(i=1;i<10;i++)
{
scanf("%d",&tmp);
p = NEW;
if(!p)
exit(-1); //检查是否成功分配空间?
p->data = tmp; //在结点中存放数据,头结点不用存放数据
q->next = p;
q = q->next; //q = p
q->next = NULL;
}
return head;
}
void printnode(struct node *head) //打印单链表
{
struct node *p;
p = head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
struct node *delnode(struct node *head, int N) //删除指定的结点
{
struct node *p,*q;
if(head == NULL)
{
printf("这是一个空链表\n");
return head;
}
p = head;
while(p->data!=N && p->next!=NULL) //寻找结点
{
q = p;
p = p->next;
}
if(p->data == N)
{
if(p == head)
head = p->next; //实际上buildnode函数并未在头结点存放数据
else
q->next = p->next;
free(p); //释放被删除的结点
}
else
printf("NOT FOUND!\n");
return head;
}
struct node *insertnode(struct node *head, int N) //在指定的结点前插入新结点
{
struct node *p, *q, *p0;
int value;
printf("请输入要insert的结点的value\n"); //建立一个新节点
scanf("%d",&value);
p0 = NEW;
p0->data = value;
p0->next = NULL;
/****我是一条可爱的分割线****/
if(head == NULL)
{
printf("这是一个空链表\n");
return head;
}
p = head;
while(p->data!=N && p->next!=NULL) //寻找结点
{
q = p;
p = p->next;
}
if(p->data == N)
{
if(p == head) //表头插入结点
{
head = p0;
p0->next = p;
}
else //表中插入结点
{
q->next = p0;
p0 ->next = p;
}
}
else //未找到指定的值,在表尾后插入结点
{
printf("NOT FOUND!\n");
p->next = p0;
p0 ->next =NULL;
}
return head;
}
程序运行结果
如果感觉不错,那就给我点个赞吧(ノ ̄▽ ̄)