title: 链表基本操作date: 2020-10-18 22:44:41
tags: C++
categories: 算法

code

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. #define MAXLEN 40
  5. #define ERROR 0
  6. #define OK 1
  7. #define NOT -1
  8. typedef struct
  9. {
  10. char ch[MAXLEN];
  11. int len;
  12. } SString;
  13. //函数:创建链表
  14. void initSString(SString *p,char ch_[MAXLEN])
  15. {
  16. strcpy(p->ch,ch_);
  17. p->len = strlen(p->ch);
  18. }
  19. //函数:在指定坐标前插入字符串(在LALB段间接上LC段)
  20. int Insert(SString *s, int pos, const SString *t)
  21. {
  22. int i;
  23. if (pos < 0 || pos > s->len) //插入位置不合法
  24. return ERROR;
  25. if (s->len + t->len <= MAXLEN) //A+B+C <= MAXLEN
  26. {
  27. for (i = s->len + t->len - 1; i >= pos + t->len; i--)
  28. s->ch[i] = s->ch[i - t->len];
  29. for (i = 0; i < t->len; i++)
  30. s->ch[i + pos] = t->ch[i];
  31. s->len = s->len + t->len;
  32. }
  33. else if (pos + t->len <= MAXLEN) //A+B <= MAXLEN C要截取
  34. {
  35. for (i = MAXLEN - 1; i >= pos + t->len; i--)
  36. s->ch[i] = s->ch[i - t->len];
  37. for (i = 0; i < t->len; i++)
  38. s->ch[i + pos] = t->ch[i];
  39. s->len = MAXLEN;
  40. }
  41. else //A <= MAXLEN BC都要截取
  42. {
  43. for (i = 0; i < MAXLEN - pos; i++)
  44. s->ch[i+pos] = t->ch[i];
  45. }
  46. return OK;
  47. }
  48. //函数:从pos下标位置开始,删除l个元素
  49. StrDelete(SString *s, int pos, int l)
  50. {
  51. int i;
  52. if (pos < 0 || pos > (s->len - l))
  53. return ERROR;
  54. for (i = pos + l; i < s->len; i++)
  55. s->ch[i - l] = s->ch[i];
  56. s->len = s->len - l;
  57. return OK;
  58. }
  59. //函数:求从主串pos下标开始,返回第一个子串首元素下标,没有返回0
  60. int index_BF(const SString *s,const SString *sub,int pos)
  61. {
  62. if(pos < 0 || pos > (s->len-1))
  63. return ERROR;
  64. int i = pos;int j = 0;
  65. int lens = strlen(s->ch);
  66. int lensub = strlen(sub->ch);
  67. while(i < lens && j < lensub)
  68. {
  69. if(s->ch[i] == sub->ch[j]){i++;j++;}
  70. else {i = i-j+1;j = 0;}
  71. }
  72. if(j >= sub->len)
  73. return i - j;
  74. else return NOT; //不是子串
  75. }
  76. main()
  77. {
  78. int t = 0;
  79. char str[100];
  80. SString s = {"abcdef",6};
  81. SString sub = {"labcde",6};
  82. SString a;
  83. cout<<"Input: "<<endl;
  84. cin>>str;
  85. initSString(&a,str);
  86. cout<<a.ch<<endl;
  87. cout<<a.len<<endl;
  88. return 0;
  89. }