这是很早之前学习数据结构时写的程序代码,放在这里留存。
功能描述:输入一大串字符串,然后使用链表来颠倒字符串的顺序,练习链表的使用。
代码如下:
#include "stdio.h"
#include "stdlib.h"
typedef struct node{
int data;
struct node * next;
}node,* pnode;
int init(pnode *,pnode *);
int insert(pnode *,pnode *);
int traverse(pnode *);
void main()
{
pnode ph=NULL,pt=NULL;
init(&ph,&pt);
insert(&ph,&pt);
traverse(&ph);
system("pause");
}
int init(pnode * ph,pnode * pt)
{
pnode h;
h=(pnode)malloc(sizeof(node));
if(!h)printf("ERROR");
h->data=0;
h->next=NULL;
*ph=*pt=h;//给传进来的指针赋值,让头指针和尾指针指向头节点
return 0;
}
int insert(pnode * ph,pnode * pt)
{
pnode p;
char ch;
//头插法
printf("输入数据:");
scanf("%c",&ch);
while(ch!='\n')
{
p=(pnode)malloc(sizeof(node));
p->data=ch;
p->next=(*ph)->next;
(*ph)->next=p;
*pt=p;
scanf("%c",&ch);
}
return 0;
}
int traverse(pnode * ph)
{
pnode p=NULL;
int i=0;
p=(*ph)->next;
while(p)
{
for(i=0;i<200000000;i++);
printf("%c ",p->data);
p=p->next;
}
printf("\n倒置结束!\n\n\n\n\n\n");
return 0;
}
效果图: