【链表的尾插法】字符串"235"正序输出,即输出为"235"
#include<iostream>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef struct charlink
{
char ch;
struct charlink *next;
} CharLink;
CharLink* createCharLink(const char *str1)
{
CharLink *p = (CharLink*)malloc(sizeof(CharLink));
p->next = NULL;
CharLink *r = p;
while(*str1)
{
CharLink *t = (CharLink*)malloc(sizeof(CharLink));
t->ch = *str1;
t->next = NULL;
p->next = t;
p= p->next;
++str1;
}
return r;
}
int main()
{
const char *str1 = "235";
CharLink *p = createCharLink(str1);
while(p->next)
{
cout << p->next->ch << endl;
p = p->next;
}
return 0;
}
【链表的头插法】字符串"235"会倒序输出,即输出为"532"
#include<iostream>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef struct charlink
{
char ch;
struct charlink *next;
} CharLink;
CharLink* createCharLink(const char *str1)
{
CharLink *p = (CharLink*)malloc(sizeof(CharLink));
p->next = NULL;
while(*str1)
{
CharLink *t = (CharLink*)malloc(sizeof(CharLink));
t->ch = *str1;
t->next = NULL;
t->next = p->next;
p->next = t;
++str1;
}
return p;
}
int main()
{
const char *str1 = "235";
CharLink *p = createCharLink(str1);
while(p->next)
{
cout << p->next->ch << endl;
p = p->next;
}
return 0;
}