在深信服面试的时候问了一道题,例如两个链表1 -> 2 -> 3, 7 ->9分别代表数字123与79,请实现两个数字相加
大概就是通过两个单链表实现数字加法的功能,这道题目与leetcode第二题较相似,只不过需要考虑数字翻转的问题。
我有两个想法,一个是逆置单链表,一个是利用两个栈实现翻转,最后用了两个栈,面试官好像更期望用逆置单链表来实现,大概更能全面展示对链表的理解,毕竟有一道题就是链表翻转,一次性全考量了
当时没能全部实现代码,现在写下完整代码记录一下:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
void printList(ListNode* l) {
ListNode* tmp = l;
while (tmp != nullptr) {
cout << tmp->val << " ";
tmp = tmp->next;
}
cout << endl;
}
void prinStack(stack<ListNode*> s) {
while (!s.empty()) {
cout << s.top()->val << " ";
s.pop();
}
cout << endl;
}
ListNode* twoNumSum(ListNode* l1, ListNode* l2) {
cout << "---------------" << endl;
stack<ListNode*> s1, s2;
ListNode* temp1 = l1;
ListNode* temp2 = l2;
while (temp1) {
s1.push(temp1);
temp1 = temp1->next;
}
while (temp2) {
s2.push(temp2);
temp2 = temp2->next;
}
int index = 0;
cout << "s1: ";
prinStack(s1);
cout << "s2: ";
prinStack(s2);
//以上调试正常
ListNode* ans = new ListNode(0);//新链表的头节点
ListNode* cur = ans;
//int ten = 0;
int one = 0;
while (!s1.empty() || !s2.empty()) {
int a = s1.empty() == true ? 0 : s1.top()->val;
int b = s2.empty() == true ? 0 : s2.top()->val;
if (!s1.empty()) s1.pop();
if (!s2.empty()) s2.pop();
int val = a + b + index;
cout << "val = " << val << endl;
index = val / 10;
one = val % 10;
cur->next = new ListNode(one);
cur = cur->next;
}
if (index > 0) {
//有进位
cur->next = new ListNode(1);
}
ListNode* head = ans->next;
cout << "l1 add l2: ";
printList(head);
stack<ListNode*> s;
while (head != nullptr) {
s.push(head);
head = head->next;
}
cout << "储存最后结果的s:";
prinStack(s);
ListNode* last = new ListNode(0);
ListNode* last1 = last;
cout << "s: ";
while (!s.empty()) {
cout << s.top()->val << " ";
//last1->next = s.top();//printList(last->next)会循环打印结果,跳不出来
last1->next = new ListNode(s.top()->val);
last1 = last1->next;
s.pop();
}
cout << endl;
cout << "最后结果链表的内容: ";
printList(last->next);
return last->next;
}
int main() {
int m, n;
while (cin >> m >> n) {
cout << "m = " << m << ", n = " << n << endl;
ListNode* dummyHead = new ListNode(0);
ListNode* cur = dummyHead;
ListNode* dummyHead2 = new ListNode(0);
ListNode* cur2 = dummyHead2;
for (int i = 0; i < m; ++i) {
int val;
cin >> val;
cur->next = new ListNode(val);
cur = cur->next;
}
cout << "dummyHead: ";
printList(dummyHead->next);
for (int i = 0; i < n; ++i) {
int val;
cin >> val;
cur2->next = new ListNode(val);
cur2 = cur2->next;
}
cout << "dummyHead2: ";
printList(dummyHead2->next);
//以上部分调试完成
ListNode* ans = twoNumSum(dummyHead->next, dummyHead2->next);
cout << "ans from twoNumSum: ";
printList(ans);
}
return 0;
system("pause");
}