单链表的插入(完整版程序c语言实现,以字符串为数据)

来源:互联网 发布:php abstract class 编辑:程序博客网 时间:2024/06/07 13:47

这里的插入主要是针对有序表中插入一个数据,插入后仍然为一个有序表。接下来会给出在链表尾插入,和在链表投插入怎么做

#include<stdio.h>#include<stdlib.h>#include<malloc.h>#include<string.h>#define N 3typedef struct node{    char name[20];    struct node *next;}ListNode;ListNode *creat(int n){    ListNode *p,*h,*s;    int i;    if((h=(ListNode*)malloc(sizeof(ListNode)))==NULL)    {        printf("不能分配内存空间!");        exit(0);    }    h->name[0] = '\0';    h->next=NULL;    p = h;    for(i = 0;i<n;i++)    {if((s=(ListNode*)malloc(sizeof(ListNode)))==NULL)    {        printf("不能分配内存空间!");        exit(0);    }p->next = s;printf("请输入第%d个人的名字",i+1);scanf("%s",s->name);s->next = NULL;p = s;    }    return(h);}void printList(ListNode *p){    while(p->next){    p = p->next;    printf("%s\n",p->name);}}void reverse(ListNode *p){  ListNode *a,*b,*c;  a = p;  b = p->next;  while(b->next!=NULL)  {      c=b->next;      b->next = a;      a = b;      b=c;  }  b->next = a;  p->next->next = NULL;  p->next=b;}void find(ListNode* head,char *t){ ListNode *p,*s; p =head; while((p->next)&&(strcmp(p->next->name,t)))     p = p->next; if(p->next) {     printf("找到了!哦耶\n"); } else {     printf("没找到,大哭!\n"); }}void Insert(ListNode* head){char t[10];ListNode *p,*s;int i,j;printf("请输入要插入的字符串:");scanf("%s",&t);p = head;j = 0;while(p->next&&strcmp(t,p->next->name)>0){    j++;    p = p->next;}if(!strcmp(t,p->next->name))  printf("重复插入,不允许。\n");else{    s = (ListNode*)malloc(sizeof(ListNode));    strcpy(s->name,t);    s->next = p->next;    p->next = s;}}void main(){    int number;    ListNode *head;    char t1[80];    char *t2;    number = N;    head = creat(number);    printf("创建好的链表为:\n");    printList(head);    //reverse(head);    //printf("单链表逆置之后:\n");    //printList(head);//printf("输入要查找的字符串\n");   // gets(t1);//scanf("%s",&t1);    //find(head,t1);Insert(head);printList(head);}

运行结果如下:
这里写图片描述

0 0
原创粉丝点击