int t = 0; while(l1 != nullptr || l2 != nullptr){ if(l1 != nullptr) t += l1 -> val, l1 = l1 -> next; if(l2 != nullptr) t += l2 -> val, l2 = l2 -> next; ListNode * node = new ListNode(t % 10); t /= 10; if(head == nullptr){ head = node; cur = node...
ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; 链表的逆 1->2->3->4->5 ^ root 想要逆序,最直接的想法,就是希望上图中的链表指向反过来。我们借用一个空指针 node 指向一个空节点: 1->2->3->4->5 | ListNode* reverse(ListNode *root) { ^ | ListNode *node = nullptr...
* 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) { stack<ListNode*>st...
ListNode* p = head; //利用尾插法创建一个链表 while (cin >> num){ ListNode* q = new ListNode(num); p->next = q; p = p->next; } //遍历这个链表,并输出每个结点的元素 ListNode* m = head; while (m != nullptr){ cout << m->val << endl; m = m->next; } return 0; } ...
由于每个数字包含的信息少于4位,因此我对每个ListNode::val使用了unsigned char(1字节)而不是int(在...
return 0; } Person.h代码 #include<iostream>usingnamespacestd;classPerson{public:intage; string name;Person(intx,string name):age(x),name(name){}intGetAge(){returnthis->age; } };structlistNode{intval; listNode *next;listNode(intx):val(x),next(nullptr){} ...
int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; bool hasCycle(ListNode *head) { if (head == NULL || head->next == NULL) { return false; } ListNode *slow = head; ListNode *fast = head->next; while (slow != fast) { ...
ListNode *next =nullptr; while(head !=nullptr) {// 将一个链表拆分为三个链表 next = head->next;// 保存下一个节点 head->next =nullptr; if(head->val < K) { if(leftHead ==nullptr) { leftHead = head; leftEnd = head; }else...
node1->next=node2; node2->next=node3; // 迭代方法逆置链表 head=reverseList(head); // 输出逆置后的链表:4 -> 3 -> 2 -> 1 -> nullptr ListNode*tempNode=head; while(tempNode!=nullptr){ std::cout<<tempNode->val<<" "; tempNode=tempNode->next; ...