串操作

问题描述:

  编写算法,求得所有包含在串S中而不包含在串T中的字符(S中重复的只选一个)构成的新串R,及R中每个字符在S中第一次出现的位置。

代码:

View Code
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct LNode{//每个结点除了保存值外,还保存位置
 4     char data;
 5     int pos;
 6     struct LNode *next;
 7 }LNode,*LinkList;
 8 void Init_L(LinkList &L)//初始化链表
 9 {
10     L=(LinkList)malloc(sizeof(LNode));
11     L->next=NULL;//带头结点的链表
12 }
13 void ListInsert_L(LinkList &L,char e,int pos)
14 {
15     LinkList s=(LinkList)malloc(sizeof(LNode));
16     s->data=e;
17     s->pos=pos;
18     s->next=L->next;
19     L->next=s;
20 }
21 void GetElme_L(LinkList L,char &e,int &pos,int i)
22 {
23     LinkList p=L->next;//L带头结点
24     int j=1;
25     while(p&&j<i){
26         p=p->next;
27         ++j;
28     }
29     e=p->data;
30     pos=p->pos;
31     if(!p)
32         printf("元素取完!");
33     //p=p->next;
34 }
35 int main()
36 {
37     LinkList L;
38     Init_L(L);
39     char a[10],b[10],c[10],e;
40     int  i=0,j=0,t=0,pos,count=0;
41     printf("请输入串S\n");
42     scanf("%s",a);
43     printf("请输入串T\n");
44     scanf("%s",b);
45     while(b[j])
46     {
47         j++;
48     }//求数组b的长度
49     while(a[i]){
50         for(int k=0;k<j;k++)
51         {
52              //if(i>0&&a[i]==a[i-1])
53             //    break;
54             if(a[i]!=b[k])
55                 continue;
56             else//相等时则跳出while循环
57                 break;
58         }
59         if(k==j)
60         {       
61           // c[t]=(i<<16)|a[i];
62            //t++;
63             ListInsert_L(L,a[i],i);
64                 t++;
65         }
66         i++;
67     }
68     //消除相同的元素,并输出每个字符在S中第一次出现的位置//   用链表的形式,顺带用上结构体
69     /*for(int count1=0;count1<t;count1++)
70         for(int count2=count1+1;count2<t;count2++)
71         {
72             if(c[count1]==c[count2])
73         }*/
74     while(count<t)
75     {
76         //printf("%c\n",c[count]);
77         //count++;
78         GetElme_L(L,e,pos,count+1);
79         printf("元素为:%c,原来的位置为:%d\n",e,pos);
80         count++;
81     }
82 }

总结:
   不太满意这道题的解法,但是自己花的时间有点多,就暂且解到这里吧,可以看出自己的基本功不扎实,很多东西不懂,弄了很久。这里用到了链表来保存在S中第一次出现的位置,不知道为什么我总感觉自己的代码想复杂了,我的思路只能想到那么些,明白要多看看,多思考,多实践才会有所提高。

原文地址:https://www.cnblogs.com/wj204/p/3052547.html