前言
这是LeetCode打卡第四天,今天的题目是回文链表,给一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
一、Python代码
class HWlist:
def __init__(self, list1):
self.list1 = list1
def hwlist(self):
z = int(0.5 * len(self.list1) if len(self.list1) % 2 ==0 else 0.5 * (len(self.list1) - 1))
for i in range(z):
if self.list1[i] != self.list1[len(self.list1)-i-1]:
print("这个列表不是回文列表")
return False
print("这个列表是回文列表")
if __name__ == "__main__":
xx = input("请输入一个列表:")
try:
xx = [int(i) for i in xx.split()]
L = HWlist(xx)
L.hwlist()
except ValueError:
print("输入错误,请输入数字")
二、C++
1.头文件
#ifndef HWLIST_H
#define HWLIST_H
#include <list>
class Hwlist
{
public:
Hwlist(std::list<int> &xx);
void hwlist();
private:
std::list<int> list1;
};
#endif
2.源文件代码
#include <iostream>
#include "hwlist.h"
using namespace std;
Hwlist::Hwlist(list<int> &xx):list1(xx)
{}
void Hwlist::hwlist()
{
int z;
list<int>::iterator ss = this->list1.begin();
list<int>::iterator ee = this->list1.end();
ee--;
if (this->list1.size() % 2 == 0)
{z = 0.5*(this->list1.size());}
else
{z = 0.5*(this->list1.size() - 1);}
for (int i = 0; i < z; i++)
{
if (*ss != *ee)
{
cout << "这个链表不是回文的" << endl;
return;
}
}
cout << "这个链表是回文的" << endl;
}
3.运行文件
#include <iostream>
#include "hwlist.h"
#include <list>
#include <sstream>
using namespace std;
int main()
{
string line;
int num;
list<int> xx;
cout << "请输入你的链表: ";
getline(cin, line);
istringstream iss(line);
while(iss >> num)
{
xx.push_back(num);
}
Hwlist LL(xx);
LL.hwlist();
}
总结
今天的收获在于学会熟练使用c++的链表list相关操作