程序员面试宝典_链表基本操作,建立,求长,删除和插入特定值的结点

来源:互联网 发布:增大音量的软件 编辑:程序博客网 时间:2024/05/22 05:22
删除data1值的结点,插入data2值的结点/*程序参见《程序员面试宝典》179页,链表长度不包含头结点,终止条件:输入0********************************************************************/#include<stdio.h>#include <stdlib.h>#include<conio.h>typedef struct student{int data;struct student *next;}node;//单链表建立过程,函数声明和定义node *creat(){node *head,*p,*s;int x,cycle=1;head=(node*)malloc(sizeof(node));if(head==NULL){printf("分配存储空间失败");exit(0);}p=head;while(cycle){printf("please input the data:");scanf("%d",&x);if(x!=0){s=(node*)malloc(sizeof(node));if(s==NULL){printf("分配存储空间失败");exit(0);}s->data=x;printf("%d\n",s->data);p->next=s;p=s;}else cycle=0;}head=head->next; //这一句的解释:head原来为指向头结点的指针(头指针),经过这句后,head指向第一个结点//单链表的长度不包含头结点,头结点位置一般设为i=0。p->next=NULL;printf("yyy %d\n",head->data);return head;}//单链表测长************************************int length(node *head){int n=0;node *p;p=head;while(p!=NULL){p=p->next;n++;}return n;}//单链表打印@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@void print(node *head){node *p;int n;n=length(head);printf("Now,these %d records are :\n",n);p=head;if(head!=NULL)while(p!=NULL){printf("uuuu  %d    \n ",p->data);p=p->next;}}<pre name="code" class="cpp">//单链表删除一个数据域为data1的结点node *del_data1(node *head,int data1){node *p1,*p2;p1=head;while(data1!=p1->data&&p1->next!=NULL){p2=p1;p1=p1->next; }if(data1==p1->data){if(p1==head)//删除第一个结点{head=p1->next;free(p1);}else p2->next=p1->next;//}elseprintf("\n%d could not been found",data1);return head;}//单链表插入一个数据域为data2的结点node *insert_data2(node *head,int data2){node *p0,*p1,*p2;p1=head;p0=(node *)malloc(sizeof(node));p0->data=data2;while(p0->data>p1->data&&p1->next!=NULL){p2=p1;p1=p1->next;}if(p0->data<=p1->data){if(head==p1)//插入位置为第一个结点之前{p0->next=p1;head=p0;}else//一般情况{p2->next=p0;p0->next=p1;}}else//插入位置为最后一个结点之后{p1->next=p0;p0->next=NULL;}return head;}
//主函数**************************int main(){    node *head1;int n1;    head1=creat();//建立    n1=length(head1);    printf("the length of the list is %d\n",n1);//求表长    print(head1);//打印    return 0;}


0 0
原创粉丝点击