如图,head2是一个值为2的单链表节点,head1是值为4的单个链表节点,我疑惑的是为什么cur->next和d明明是同一个变量,在调试时却是一个为2,一个没有初始化。完整代码有点长,不过不重要,是实现一个链表的归并排序。
我想要达到的结果
```c++
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* sortList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
int a = head->val;
ListNode* fast = head;
ListNode* slow = head;
ListNode* brk = nullptr;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
if (fast == NULL || fast->next == NULL)
brk = slow;
slow = slow->next;
}
brk->next = nullptr;
ListNode* head1 = sortList(head);
int b = head1->val;
ListNode* head2 = sortList(slow);
int c = head2->val;
ListNode dummy(0);
ListNode* cur = &dummy;
while (head1 != nullptr || head2 != nullptr) {
if (head1 == nullptr || (head1 != nullptr && head2 != nullptr && head1->val >= head2->val)) {
cur->next = head2;
head2 = head2->next;
int e = cur->next->val;
cur = cur->next;
int d = cur->val;
}
else {
cur->next = head1;
head1 = head1->next;
cur = cur->next;
}
}
return dummy.next;
}
};
Solution solution;
int main() {
ListNode * four = new ListNode(3, nullptr);
ListNode * three = new ListNode(1, four);
ListNode *two = new ListNode(2,three);
ListNode* head = new ListNode(4, two);
ListNode* temp = head;
solution.sortList(head);
return 0;
}