文章目录
- 1. LeetCode 206 反转链表
- 2. NC40 链表相加
1. LeetCode 206 反转链表
题目链接🔗
解题思路: 🔍
🐧创建一个新的节点,使用链表头插的方法;
2. NC40 链表相加
题目链接🔗
解题思路: 🔍
🐧 将两个链表进行逆置,然后再创建一个结果集的链表,利用头插,将结果插入;
class Solution {
public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类*/ListNode* addInList(ListNode* head1, ListNode* head2) {// write code hereListNode* 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;elsek = 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;}