Leetcode shortlist sort

Source: Internet
Author: User
Sort by linked list: algorithm-merge sort public class sort {Private Static class listnode {int val; listnode next; listnode (int x) {val = x; next = NULL ;}} private listnode mergelist (listnode head1, listnode head2) {If (head1 = NULL) {return head2;} else if (head2 = NULL) {return head1 ;} listnode head = new listnode (0); listnode TMP = head; while (head1! = NULL & head2! = NULL) {If (head1.val <= head2.val) {head. next = head1; head1 = head1.next;} else {head. next = head2; head2 = head2.next;} head = head. next;} while (head1! = NULL) {head. Next = head1; head1 = head1.next; head = head. Next;} while (head2! = NULL) {head. next = head2; head2 = head2.next; head = head. next;} return TMP. next; // note that a new node is created.} public listnode sortlist (listnode head) {If (Head = NULL | head. next = NULL) {return head;} listnode first = head; listnode after = head; // If (head. next. next = NULL) {First = head. next; head. next = NULL; return mergelist (Head, first);} while (after! = NULL) {If (after. Next! = NULL) {after = after. next. next; first = first. next;} else {break;} listnode TMP = first. next; first. next = NULL; // This is prone to problems. In advance, the backend node is null listnode head1 = sortlist (head); listnode head2 = sortlist (TMP); Return mergelist (head1, head2);} public static void main (string [] ARGs) {response sort = new response sort (); listnode head1 = new listnode (9); head1.next = new listnode (3 ); head1.next. next = new listnode (4); H Ead1.next. next. next = new listnode (1); head1.next. next. next. next = new listnode (5); listnode head = javassort. sortlist (head1); system. out. println ("fuck"); While (Head! = NULL) {system. Out. println (head. Val); Head = head. Next ;}}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.