Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Update 0148-sort-list.java#2479

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
a93a merged 2 commits intoneetcode-gh:mainfromAnukriti167:patch-4
May 17, 2023
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletionsjava/0148-sort-list.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,64 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
// Merge Sort Implementation
public ListNode getMid(ListNode head){
ListNode slow=head, fast=head.next;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public ListNode merge(ListNode left, ListNode right){
ListNode dummy = new ListNode();
ListNode tail = dummy;

while(left != null && right != null){
if(left.val < right.val){
tail.next = left;
left = left.next;
}else{
tail.next = right;
right = right.next;
}
tail = tail.next;
}
if(left != null){
tail.next = left;
}
if(right != null){
tail.next = right;
}
return dummy.next;
}
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}

// Split the list in 2 halfs
ListNode left = head;
ListNode right = getMid(head);
ListNode tmp = right.next;
right.next = null;
right = tmp;

left = sortList(left);
right = sortList(right);
return merge(left, right);
}
}

// Using a Heap to sort the list
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp