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

目录

解法一

1.判断是否为回文链表

2.创建链表

3.打印链表

4.调用demo


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

解法一

1.判断是否为回文链表

#include  
#include 
using namespace std;

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

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

	stack 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<<"分配内存失败"<>len;
	int val;
	mylist *ptail=head;
	for (int i=0;i>val;
		mylist* pnode=(mylist*)malloc(sizeof(mylist));
		if (pnode==nullptr)
		{
			cout<<"分配内存失败:"<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<value<<" ";
		ptm=ptm->next;
	}
	cout<

4.调用demo

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

参考阅读:

Leetcode 234. 回文链表(进阶)

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

你可能感兴趣的:(C++开发面试题,leetcode,链表,面试,数据结构)