[LeetCode] 148. Merge Two Sorted Lists
[Question]
Sort a linked list in O (n log n) time using constant space complexity.
[Analysis]
A single-chain table is suitable for Merge Sorting, and a two-way linked list is suitable for quick sorting. The Merge Two Sorted Lists method can be reused.
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 148. merge Two Sorted Lists * Source: https://oj.leetcode.com/problems/sort-list/* result: AC * Source: LeetCode * blog: * *********************************/# include
# Include
Using namespace std; struct ListNode {int val; ListNode * next; ListNode (int x): val (x), next (NULL) {}}; class Solution {public: listNode * sortList (ListNode * head) {// fault tolerance Processing if (head = NULL | head-> next = NULL) {return head ;} // if // define two pointers ListNode * fast = head, * slow = head; // slow pointer to find the intermediate node while (fast-> next! = NULL & fast-> next! = NULL) {// fast pointer one-time two-step fast = fast-> next; // slow pointer one-step slow = slow-> next ;} /// while // disconnect from the intermediate node fast = slow-> next; slow-> next = NULL; // sort the ListNode * left = sortList (head ); // ListNode * right = sortList (fast); // return mergeTwoLists (left, right);} private: ListNode * mergeTwoLists (ListNode * l1, listNode * l2) {ListNode * head = new ListNode (-1); for (ListNode * p = head; l1! = NULL | l2! = NULL; p = p-> next) {int val1 = (l1 = NULL )? INT_MAX: l1-> val; int val2 = (l2 = NULL )? INT_MAX: l2-> val; if (val1 <= val2) {p-> next = l1; l1 = l1-> next ;} // if else {p-> next = l2; l2 = l2-> next;} // else} // for return head-> next ;}; int main () {Solution solution; int A [] = {8, 3, 10, 5, 11, 1, 4}; // linked list ListNode * head = new ListNode (A [0]); listNode * p = head; for (int I = 1; I <7; I ++) {ListNode * node = new ListNode (A [I]); p-> next = node; p = node;} // for head = solution. sortList (head); // output p = head; while (p) {cout <
Val <"; p = p-> next;} // while cout <