算是洗刷了前面第一天的那道题目。回文链表过于简单,只附代码。
几个问题:1. 注意对于链表节点重新赋值,需要将上一节点连过来;
2. 注意NULL,注意NULL,注意NULL。
第一题
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Plus {
public:
ListNode* plusAB(ListNode* a, ListNode* b) {
// write code here
if (!a) return b;
if (!b) return a;
ListNode *temp = a, *pre;
int digit = 0;
while(temp || b || digit)
{
if (temp && b)
temp->val += b->val;
else if (!temp)
{
temp = b;
pre->next = temp;
}
if (!temp && digit)
{
temp = new ListNode(1);
pre->next = temp;
return a;
}
temp->val += digit;
digit = temp->val / 10;
temp->val = temp->val % 10;
pre = temp;
if (temp)
temp = temp->next;
if (b)
b = b->next;
}
return a;
}
};
第二题
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Palindrome {
public:
// 顺序过一遍,把值取出来
bool isPalindrome(ListNode* pHead) {
// write code here
if (!pHead) return true;
vector<int> v;
while(pHead)
{
v.push_back(pHead->val);
pHead = pHead->next;
}
for(int i = 0; i < v.size(); i++)
if (v[i] != v[v.size() - 1 - i]) return false;
return true;
}
};
本文介绍两道链表操作题目:链表加法与判断链表是否为回文。通过具体的代码实现展示了如何处理链表节点的加法运算,并考虑进位情况;同时提供了一种简便的方法来判断链表是否为回文结构。
1232

被折叠的 条评论
为什么被折叠?



