指定长度的单链表,删除和插入第i个结点

来源:互联网 发布:数据分析作图软件 编辑:程序博客网 时间:2024/05/16 01:20
指定表长度为n,输入n个之后终止循环。删除和插入特定位置上的结点,如删除第i个结点此程序包含头结点指定表长度n#include <stdlib.h>#include <stdio.h>const int n=3;//事先规定链表长度为ntypedef 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
0 0
原创粉丝点击