链表题目---3 合并两个有序单链表 和 分割链表
生活随笔
收集整理的這篇文章主要介紹了
链表题目---3 合并两个有序单链表 和 分割链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
合并兩個有序單鏈表
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){if(l1 == NULL){return l2;}else if(l2 == NULL){return l1;}struct ListNode *cur1 = l1;struct ListNode *cur2 = l2;struct ListNode *result =NULL; //合并后的新鏈表struct ListNode *result_tail =NULL; //result 鏈表的最后一個結點while(cur1!=NULL&&cur2!=NULL){if(cur1->val <= cur2->val ){//把cur1的結點尾插到resultif(result_tail !=NULL){ //往最后一個結點插result_tail->next=cur1;result_tail=cur1;}else{result =cur1;result_tail=cur1;}cur1=cur1->next; //往后移}else{//把cur2的結點尾插到resultif(result_tail !=NULL){result_tail->next=cur2;result_tail=cur2;}else{result =cur2;result_tail=cur2;}cur2=cur2->next; //往后移}}//一個鏈表已經處理完了if(cur1 != NULL){result_tail->next=cur1;}else{result_tail->next=cur2;}return result; }分割鏈表
/* struct ListNode {int val;struct ListNode *next;ListNode(int x) : val(x), next(NULL) {} };*/ class Partition { public:ListNode* partition(ListNode* pHead, int x) {ListNode *lt =NULL; // <x的第一個結點ListNode *lt_tail =NULL; //<x 的最后一個結點ListNode *ge =NULL; // >=x的第一個結點ListNode *ge_tail = NULL; // >=x 的最后一個結點ListNode *cur =pHead;while(cur != NULL){ListNode *next =cur->next;cur->next = NULL;if(cur->val< x){if(lt_tail == NULL){lt = lt_tail =cur;}else{lt_tail->next = cur;lt_tail = cur;}}else{if(ge_tail == NULL){ge = ge_tail =cur;}else{ge_tail->next = cur;ge_tail = cur;}}cur = next;}if(lt_tail == NULL){return ge;}lt_tail->next = ge;return lt;} };總結
以上是生活随笔為你收集整理的链表题目---3 合并两个有序单链表 和 分割链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css选择器,不唯一怎么表示? 财
- 下一篇: 链表题目---4 删除链表中重复的结