String_LinkList(串的鏈式存儲)

/*代碼存在問題*/


#include<stdio.h>
typedef struct node {
char data;
struct node *next;
}linkstrnode;
typedef linkstrnode *linkstring;


void display(linkstring s);
void strconcat(linkstring *s1, linkstring s2);
void strcreate(linkstring *s)
{
char ch;
linkstrnode *p;
linkstrnode *r;
*s = NULL; 
r = NULL;
while ((ch = getchar()) != '\n')
{
p = (linkstrnode*)malloc(sizeof(linkstrnode));
p->data = ch;
if (*s == NULL)
*s = p;
else
r->next = p;
r = p;
}
//if (r != NULL)
r->next = NULL;
}


void strinsert(linkstring *s, int i, linkstring t)
{
int k=1;
linkstring p,q;
linkstring r;
p = *s;
while (p&&k < i - 1)
{
p = p->next;
++k;
}
r = p->next;
if (!p)
printf("error!\n");
else
{
q = (linkstring)malloc(sizeof(linkstrnode));
q = t;
while (q&&q->next)
q = q->next;
q->next = r;
p->next = t;
}

}


void strdele(linkstring *s, int i, int len)
{
int k = 1;
linkstring p, q;
p = *s;
while (p&&k < i - 1)
{
p = p->next;
++k;
}
if (!p)
printf("error!\n");
else
{
k = 0;
q = p->next;
while (k < len-1)
{
q = q->next;
++k;
}
p->next = q->next;
}
}


void strconcat(linkstring *s1, linkstring s2)
{
linkstring p;
if (!(*s1))
{
*s1 = s2;
return;
}
else
if (s2)
{
p = *s1;
while (p->next)
p = p->next;
printf("找到尾部1!\n");
p->next = s2;
while (s2->next)
s2 = s2->next;
printf("找到尾部2!\n");
s2->next = NULL;
}
}


linkstring substring(linkstring s, int i, int len)
{
int k; linkstring p, q, r, t;
p = s;
k = 1;
while (p&&k < i)
{
p = p->next;
k++;
}
if (!p)
{
printf("error!");
return NULL;
}
else
{
r = (linkstring)malloc(sizeof(linkstrnode));
r->data = p->data; r->next = NULL;
k = 1;
q = r;
while (p->next&&k < len)
{
p = p->next;
k++;
t = (linkstring)malloc(sizeof(linkstrnode));
t->data = p->data;
q->next = t;
q = t;
}
if (k < len)
{
printf("error 2");
return NULL;
}
else
{
q->next = NULL;
return r;
}
}
}


void display(linkstring s)
{
linkstrnode *r= s;
while (r!=NULL)
{
printf("%5c", r->data);
r = r->next;
}
putchar('\n');
}


void main()
{
linkstring *S;
S = (linkstring *)malloc(sizeof(linkstring));
*S = NULL;
strcreate(&S);
display(S);
linkstring *T;
T = (linkstring *)malloc(sizeof(linkstring));
*T = NULL;
strcreate(&T);
display(T);
strinsert(&S, 3, T);//對T造成了影響
printf("strinsert:");
display(S);
strdele(&S, 3, 1);
printf("strdele:");
display(S);
linkstring a;
a=substring(S, 3, 6);
printf("substring:");
display(a);
strconcat(&a, T);
printf("strconcat:");
display(a);
display(T);
}

發佈了46 篇原創文章 · 獲贊 16 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章