【LeetCode 链表合集】
1. LeetCode 206 反转链表
解题思路: 🔍
🐧创建一个新的节点,使用链表头插的方法;
2. NC40 链表相加
解题思路: 🔍
🐧 将两个链表进行逆置,然后再创建一个结果集的链表,利用头插,将结果插入;
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* newHead1 = new ListNode(0);
// 先将链表逆置
ListNode* cur1 = head1;
while (cur1 != nullptr)
{
ListNode* tmp = cur1->next;
cur1->next = newHead1->next;
newHead1->next = cur1;
cur1 = tmp;
}
// 将链表逆置
ListNode* newHead2 = new ListNode(0);
ListNode* cur2 = head2;
while (cur2 != nullptr)
{
ListNode* tmp = cur2->next;
cur2->next = newHead2->next;
newHead2->next = cur2;
cur2 = tmp;
}
ListNode* resHead = new ListNode(0);
cur1 = newHead1->next;
cur2 = newHead2->next;
int k = 0;
while (cur1 || cur2)
{
int num1 = 0;
if (cur1 != nullptr)
num1 = cur1->val;
int num2 = 0;
if (cur2 != nullptr)
num2 = cur2->val;
// 每次把结果头插
int num = num1 + num2 + k;
if (num >= 10)
k = 1;
else
k = 0;
num %= 10;
ListNode* numNode = new ListNode(num);
numNode->next = resHead->next;
resHead->next = numNode;
if (cur1 != nullptr)
cur1 = cur1->next;
if (cur2 != nullptr)
cur2 = cur2->next;
}
if (k > 0)
{
ListNode* numNode = new ListNode(1);
numNode->next = resHead->next;
resHead->next = numNode;
}
return resHead->next;
}
原文地址:https://blog.csdn.net/Hou_lang_LJ/article/details/140421581
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!