栈-链表
普通链表的创建:
用链表构建一串数字,并输入另一个数插入其中。
以及链表的逆序。
#include<stdio.h>
#include<stdlib.h>
struct node //链表的结构体创建
{
int data;
struct node *next;
};
int main()
{
struct node *p,*q,*head,*t,*k,*num;
int i,n,a,s;
scanf("%d",&n);
head=NULL;
for(i=0;i<n;++i){ //链表的创建
scanf("%d",&a);
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
t=head;
k=head->next;
scanf("%d",&s);
for(i=0;i<n;++i){ //链表的插入
if(t->data<s&&k->data>=s){
p=(struct node *)malloc(sizeof(struct node));
p->data=s;
t->next=p;
p->next=k;
break;
}
else{
t=t->next;
k=k->next;
}
}
struct node *x,*y;
x=head->next;
head->next=NULL;
while(x){ //链表的逆置
y=x;
x=x->next;
y->next=head;
head=y;
}
num=head;
while(num!=NULL){ //链表的输出
printf("%d",num->data);
num=num->next;
}
return 0;
}
普通栈的创建:
判断输入的字符串是不是回文字符串?
#include<stdio.h>
#include<string.h>
int main()
{
char a[101],s[101];
int i,len,mid,next,top;
gets(a);
len=strlen(a);
mid=len/2-1;
top=0;
for(i=0;i<=mid;++i)
s[++top]=a[i];
if(len%2==0)
next=mid+1;
else
next=mid+2;
for(i=next;i<=len-1;++i){
if(a[i]!=s[top])
break;
top--;
}
if(top==0)
printf("yes");
else
printf("no");
return 0;
}
现在用链表代替数组解决上面的问题,只需要将链表放到数组应该在的位置即可:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char data;
struct node *next;
};
int main()
{
struct node *p,*q,*head,*t,*k,*num;
int len=0,i,mid,top;
char a,s[101];
head=NULL;
printf("ÇëÊäÈë×Ö·û´®²¢ÔÚ½áÊøʱÊäÈë'.'\n");
scanf("%c",&a);
//跟普通构建链表的区别是,我这里用‘。’做判断标准,所以用do-while先输再判断。
do{
len++;
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
scanf("%c",&a);
}while(a!='.');
//类似栈的初始化,只不过把数组的变化变成了链表的变化。
p=head;
top=0;
mid=len/2-1;
for(i=0;i<=mid;++i){
s[++top]=p->data;
p=p->next;
}
if(len%2)
p=p->next;
//这里用来判断是奇数or偶数长的字符串
while(top){
if(p->data!=s[top])
break;
p=p->next;
top--;
}
if(top==0)
printf("yes");
else
printf("no");
}