面试题(29)|数据结构(8):判断一个链表是否为回文链表,说出你的思路并手写代码

目录

解法一

1.判断是否为回文链表

2.创建链表

3.打印链表

4.调用demo


更多见C++面试题系列:链表我的leecode学习笔记

解法一

1.判断是否为回文链表

#include <stack> 
#include <iostream>
using namespace std;

typedef struct mylist
{
	int value;
	mylist *next;
};

bool is_palindromic_list(mylist *a_list)
{
	if (a_list == nullptr)
	{
		return false;
	}

	stack<int> list_value;
	mylist *fast, *slow;
	while (fast->next != nullptr && fast->next->next != nullptr)
	{
		list_value.push(slow->next->value);
		slow = slow->next;
		fast = fast->next->next;
	}

	cout << "middle elem value is" << slow->next->value << endl;

	if (fast->next != nullptr)
	{
		cout << "the list has odd num of node" << endl;
		slow = slow->next;
	}

	int curvalue;
	while (!list_value.empty())
	{
		curvalue = list_value.top();
		cout << "stack top value is" << curvalue << endl;
		cout << "list value is" << slow->next->value << endl;
		if (curvalue != slow->next->value)
		{
			return false;
		}

		list_value.pop();
		slow = slow->next;
	}

	return true;
}

2.创建链表

//创建链表
mylist* CreateList()
{
	mylist* head=NULL;
	//1.创建头结点
	head =(mylist*) malloc(sizeof(mylist));
	if (head == nullptr)
	{
		cout<<"分配内存失败"<<endl;
		return head;
	}
	int len;
	cout<<"输入节点个数:"<<endl;
	cin>>len;
	int val;
	mylist *ptail=head;
	for (int i=0;i<len;i++)
	{
		cin>>val;
		mylist* pnode=(mylist*)malloc(sizeof(mylist));
		if (pnode==nullptr)
		{
			cout<<"分配内存失败:"<<i<<endl;
			return nullptr;
		}
		pnode->value=val;
		pnode->next=nullptr;
		ptail->next=pnode;
		ptail = pnode;		
	}
	return head;
}

3.打印链表

//打印链表
void printList(mylist *head)
{
	if (head==nullptr)
	{
		return;
	}
	mylist *ptm=head->next;
	while(ptm)
	{
		cout<<ptm->value<<" ";
		ptm=ptm->next;
	}
	cout<<endl;
}

4.调用demo

int _tmain(int argc, _TCHAR* argv[])
{
	mylist* head=CreateList();
	printList(head);
	bool res=Is_palindromic_list(head);
	if (res)
	{
		cout<<"链表是回文链表"<<endl;
	} 
	else
	{
		cout<<"不是回文链表"<<endl;
	}
	return 0;
}

参考阅读:

Leetcode 234. 回文链表(进阶)

链表:创建一个简单的链表并输出链表内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haimianjie2012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值