Sort a linked list using insertion sort.
Example:
Input: 5->2->8->4->1->NULL
Output: 1->2->4->5->8->NULL
Approach
Java
public class InsertionSortList {public static void main(String[] args) {ListNode l = new ListNode(1);l.next = new ListNode(2);l.next.next = new ListNode(3);l.next.next.next = new ListNode(4);l.next.next.next.next = new ListNode(5);ListNode sortList = insertionSortList(l);linkedListTraversal(sortList);}// method to sort the listprivate static ListNode insertionSortList(ListNode head) {ListNode temp = head;ListNode ans = null;while (temp != null) {ListNode curr = temp.next;ans = SortedList(ans, temp);temp = curr;}return ans;}// insert the node at its correct positionprivate static ListNode SortedList(ListNode head, ListNode new_node) {if (head == null || head.val >= new_node.val) {new_node.next = head;head = new_node;return head;} else {ListNode temp = head;while (temp.next != null && temp.next.val < new_node.val)temp = temp.next;new_node.next = temp.next;temp.next = new_node;}return head;}private static void linkedListTraversal(ListNode node) {while (node != null) {System.out.print(node.val + " ");node = node.next;}}}class ListNode implements Comparable<ListNode> {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}@Overridepublic int compareTo(ListNode o) {if (this.val == o.val)return 0;else if (this.val > o.val)return 1;elsereturn -1;}}
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//function to traverse(print) a linked//listvoid linkedListTraversal(Node *head){Node *temp=head;//iterate till we reach end of the linked//listwhile(temp!=NULL){//print the current//node datacout<<temp->data<<" ";//move to next nodetemp=temp->next;}}//insert the node at its correct positionNode *SortedList(Node *head,Node *new_node){if(head==NULL ||head->data>=new_node->data){new_node->next=head;head=new_node;return head;}else{Node *temp=head;while(temp->next!=NULL&&temp->next->data<new_node->data)temp=temp->next;new_node->next=temp->next;temp->next=new_node;}return head;}//function to sort the linked//listNode* insertionSortList(Node* head){Node *temp=head;Node *ans=NULL;while(temp!=NULL){Node *curr=temp->next;ans=SortedList(ans,temp);temp=curr;}return ans;}int main(){Node *head=new Node(5);head->next=new Node(2);head->next->next=new Node(8);head->next->next->next=new Node(4);head->next->next->next->next=new Node(1);head=insertionSortList(head);cout<<"List after sort is\n";linkedListTraversal(head);return 0;}
No comments:
Post a Comment