链表结构
struct ListNode{ int val; ListNode *next; ListNode(int x):val(x), next(nullptr) {} };
206.翻转链表
翻转链表:链表“指针”翻转
1->2->3->4->5->null
null<-1<-2<-3<-4<-5
ListNode* reverseList(ListNode* head){ ListNode *prev = nullptr, *next; while(head){ next = head->next; //保存下一个(右)节点指针值 head->next = prev; //翻转当前节点指针方向 prev = head; //前(左)节点后移 head=next; //当前节点后移 } return prev; //当前节点head为null,前(左)节点prev就是翻转后的头节点 }
21.合并两个增序链表
描述:给定两个增序链表,试将其合并成一个增序的链表
input:1->2->4,1->3->4
output:1->1->2->3->4->4
ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *dummy = new ListNode(0), *node = dummy; //node作为一个临时指针 while(l1 && l2){ if(l1->val <= l2->val) { node->next=l1; l1=l1->next; }else{ node->next=l2; l2=l2->next; } node=node->next; } node->next=l1? l1:l2; //这个是重点 return dummy->next; }
类型: