C语言:栈-链表

栈-链表

普通链表的创建:
用链表构建一串数字,并输入另一个数插入其中。
以及链表的逆序。

#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");
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值