#include<stdio.h>
#include<stdlib.h>
struct node *create()
void print_list(struct node *head)
struct node * insert_node(struct node *h,int x,int y)
struct node * delete_node(struct node *h,int z)
void shifang(struct node *head)
struct node
{
char data
struct node *next
}
void main()
{
struct node *head
int x,y,z
head=create()
print_list(head)
printf("\n输入插入结点的位置的值和插入的数值:")
scanf("%d%d",&x,&y)
head=insert_node(head,x,y)
print_list(head)
printf("\n输入要删除的结点:")
scanf("%d",&z)
head=delete_node(head,z)
print_list(head)
printf("\n释放链表.\n")
}
struct node *create() //建立链表函数
{
printf("请输入各节点(以-1结尾):\n")
int x
//定义指针*head,*tail,*s
struct node *head,*tail,*s
//head和tail初始化,生成一个头结点
head=tail=(struct node *)malloc(sizeof(struct node))
//在循环中,生成新结点、赋值、连接、尾指针后移
scanf("%d",&x)
while(x!=-1)
{
s=(struct node *)malloc(sizeof(struct node))
s->data=x
tail->next=s
tail=s
scanf("%d",&x)
}
//尾结点的指针域赋NULL
tail->next=NULL
return head
}
void print_list(struct node *head)//输出链表函数
{
//定义工作指针*p并赋初值p=head->next;即指向第一个结点
struct node *p
p=head->next
//判断链表是否为空,空:输出空表的信息,否则:输出所有结点
if(p==NULL)
printf("The list is NULL.")
else
//在循环中输出当前结点,工作指针后移
{
printf("head->")
while(p!=NULL)
{
printf("%d->",p->data)
p=p->next
}
printf("end.")
}
}
struct node * insert_node(struct node *h,int x,int y) //添加结点函数
{
struct node *p,*q,*s
//生成要插入的新结点
s=(struct node *)malloc(sizeof(struct node))
s->data=y
q=h
p=h->next
//查找要插入结点的位置
while((p!=NULL)&&(p->data!=x))
{
q=p
p=p->next
}
//插入结点
q->next=ss->next=p
return(h)
}
struct node * delete_node(struct node *h,int z) //删除结点函数
{
struct node *p,*q
q=h
p=h->next
//查找要删除结点的位置
if(p!=NULL)
{
while((p!=NULL)&&(p->data!=z))
{
q=p
p=p->next
}
//释放结点
if(p->data ==z)
{
q->next=p->next
free(p)
}
}
return(h)
}
void shifang(struct node *head) //释放链表函数
{
struct node *p
//逐个释放结点
while(head!=NULL)
{
p=head
head=head->next
free(p)
}
}
#include <stdio.h>#include <stdlib.h>
struct node //定义结构体
{
int data //存放数据
struct node* next //指向下一个结点
}
struct node* Create() //新建结点并初始化
{
struct node* n=(struct node*)malloc(sizeof(struct node)*1)
n->data
n->next=NULL
return n
}
int main()
{
struct node *head=NULL,*p=NULL
int in
while(1)
{
fflush(stdin) //清空输入缓冲区
scanf("%d",&in)
if(in==-1) break //如果输入的是-1则表示用户结束输入
struct node *new_node
new_node=Create() //新建结点
new_node->data=in //把用户输入的数据存储入新结点中
if(head==NULL) //如果头结点为空,则把当前新结点当成头结点
{
head=new_node
p=head //当前指向为头结点
}
else //如果头结点不为空
{
p->next=new_node //把上一个结点的next指向新建结点
p=p->next //当前指向为新结点
}
}
p=head //重新指向头结点,以便输出
while(1)
{
printf("\n%d",p->data) //输出数据字符串
if(p->next==NULL) break //如果当前结点没有指向下一个结点,则退出
p=p->next //当前指向下一个结点
}
return 0
}