当前位置:C++技术网 > 资讯 > 用单链表如何操作字符串

用单链表如何操作字符串

更新时间:2015-11-10 16:57:13浏览次数:1+次

字符串的操作向来是编程算法的经典问题,单链表又是数据结构中比较重要的一部分,所以今天就给大家介绍一下用单链表如何操作字符串。


#include <stdio.h>
#include <string.h>
#define null 0
typedef struct node{
  char *data;//结点的数据域,为一个字符串
  struct node *next;//结点的指针域
 }linkstrnode;//定义单链表结点结构
typedef linkstrnode *linkstring;

main(){//建立数据域为字符串类型,且结点无重复的单链表。对单链表做删除结点操作

  linkstring head;
  char *t;

  printf("\nplease input the node of the linklist:");
  printf("\nnodes data is strings,and end of #\n");
  creatlinkstr(&head);//建立单链表
  printf("\nthe source linklist is :\n");
  printing(head);//输出单链表
  printf("\nplease input search string:");
  gets(t);//输入要删除的字符串
  deletet(&head,t);//在单链表head中找到并删除值与t相同的结点
  printf("\nthe final linklist is:\n");
  printing(head);//输出做了删除操作后的单链表
 }

creatlinkstr(linkstring head){
  //建立单链表
  char *t;
  linkstrnode *p;
  head=(linkstrnode *)malloc(sizeof(linkstrnode));
   //建立一个只含头结点的空链表,头指针为head
  head->next=null; 
  printf("\nplease input the node data(string),end of #");
  gets(t);//输入一个字符串t
  while (strcmp(t,"#")!=0){//当t的值不为“#”时,做以下操作
    p=head;//在建好的单链表中,以p为扫描指针,从头开始查找有无数据域与t相同的结点
    while ((p->next)&&(strcmp(t,p->next->data)))
      p=p->next;
    if (p->next)//如果存在数据域与t相同的结点,则输出存在信息
      printf("\nstring %s existed",t);
    else{//若不存在数据域与t相同结点,则做以下操作
      p->next=(linkstrnode *)malloc(sizeof(linkstrnode));
       //在单链表表尾申请一个新结点
      p=p->next;//p指针指向新的表尾结点
      strcpy(p->data,t);//将t的值复制到*p结点的数据域中
      p->next=null;//将单链表的表尾结点的next指针置为空
     }
    printf("\nplease input the node data(string),end of #");
    gets(t);//输入下一个字符串
  }//end of while
 }//end of creatlinkstr

printing(linkstring head){
  //输出head单链表
  linkstrnode *p;
  p=head->next;
  while(p){
    puts(p->data);//输出结点的数据——字符串
    p=p->next;
   }
 }//end of printing

deletet(linkstring head,char *t){
  //若head单链表中有数据为t的结点,删除之
  linkstrnode *p,*s;
  p=head;
  while ((p->next)&&(strcmp(p->next->data,t)))
  //以p为扫描指针对head链表进行查找数据域值为*t结点,
  //为了能方便删除操作,p指向待查结点的前趋
   p=p->next;
  if (p->next){//若查找到有,则做删除操作
    s=p->next;
    p->next=s->next;
    free(s);
    printf("\ndelete successful!");
   }
  else//若head链表中没有数据域的值为*t的结点,则输出删除失败的信息 
    printf("\ndelete failure!");
 }