链表题目,假设链表头Listnode *head,创建后续节点(赋值)必须是要tail=head;tail->next=new Listnode(1); tail=tail->next;
而不能tail=head->next;tail=new Listnode(1);
new的左边必须有个next,否则这个new出来的内存空间不会和原本链表头相连。
因为本身next指向的是空,还没有指向一个确切的内存地址,所以temp=a->next是没有意义的,就相当于temp=null;
必须temp先与head绑定,再给里面的next开辟内存空间
为什么有时候要额外分情况讨论链表头head是否为空呢,因为此时head为nullptr时没有next成员,不能直接head->next,
需要先为其分配空间head=new Listnode(1),当其不为空之后再用tail->next
以leetcode经典题目两数相加举例
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + carry;
if (!head) {
head = tail = new ListNode(sum % 10);
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (carry > 0) {
tail->next = new ListNode(carry);
}
return head;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/add-two-numbers/solutions/435246/liang-shu-xiang-jia-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。