指定表长度为n,输入n个之后终止循环。删除和插入特定位置上的结点,如删除第i个结点
此程序包含头结点
指定表长度n
#include <stdlib.h>
#include <stdio.h>
const int n=3;//事先规定链表长度为n
typedef struct node
{
int data;
struct node *next;
}node;
//单链表的建立函数*********
node *creat(int n1)
{
node *head,*p,*s;
int i=0;
head=(node*)malloc(sizeof(node));
p=head;
if(head==NULL)
{
printf("存储分配失败");
exit(1);
}
for(i=1;i<=n1;i++)
{
s=(node*)malloc(sizeof(node));
if(s==NULL)
{
printf("存储分配失败");
exit(1);
}
printf("please input the data: ");
scanf("\n%d",&s->data);
printf("\n%d\n",s->data);
p->next=s;
p=s;
}
//head=head->next;
p->next=NULL;
return head;
}
//打印表到屏幕*********************************************************
void print(node *head)
{
node *p;
p=head->next;//head为头指针,头指针指向的结点没有数据域,所以不输出
printf("\n these %d records are: \n",n);
if(head!=NULL)
while(p!=NULL)
{
printf("\n uuuuuuuu %d",p->data);
p=p->next;
}
}
//删除第i个结点元素************************************
node *delete_i(node *head,int i)
{
node *p,*q;
int j;
int data1;
p=head;
if(i<1||i>n)
{
printf("\nerror");
exit(0);
}
else
{
j=0;
while(j<i-1)
{
p=p->next;
j++;
}
q=p->next;
p->next=q->next;
data1=q->data;
free(q);
printf("\n被删除的结点的数据元素=%d",data1);
}
}
//在第i个结点之前插入一个结点************************************
node* insert_i(node *head,int i,int data2)//data2为被插入的结点的数据域
{
node *p,*s;
int j;
p=head;
if(i<1||i>n+1)
{
printf("\n error");
exit(0);
}
else
{
j=0;
while(j<i-1)
{
p=p->next;
j++;
}
s=(node*)malloc(sizeof(node));//为插入的结点分配空间
s->data=data2;//插入的结点数据域
s->next=p->next;
p->next=s;
}
return head;
}
int main()
{
node*head1,*p;
head1=creat(n);//单链表的建立,head1为头指针
p=head1;
print(head1);//打印单链表
head1=delete_i(head1,0);//删除第0个结点,直接跳出程序
head1=insert_i(p,2,2);
print(head1);
return 0;
}
转自http://www.cnblogs.com/tao560532/articles/2199280.html