Skip to content

Commit

Permalink
Update 147.Insertion Sort List.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
jeannotes authored Aug 28, 2024
1 parent 0227920 commit 9786836
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions 147.Insertion Sort List.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,53 @@ class Solution {
return dummy->next;
}
};

https://www.programiz.com/cpp-programming/online-compiler/
// Online C++ compiler to run C++ program online
#include <iostream>

struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};


class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(head == NULL || head->next == NULL ) return head;
ListNode *dummy = new ListNode(0), *cur = head;
// dummy->next=head;
while(cur){
std::cout << "out:: " << cur->val<< std::endl;
ListNode *prev = dummy, *next = cur->next;
while(prev->next && prev->next->val<=cur->val){
std::cout << "in:: " << prev->next->val<< std::endl;
// 0,4,2,5
prev = prev->next;
}
cur->next = prev->next;
prev->next=cur;
std::cout << "last:: " << prev->next->val<< std::endl;
cur = next;
}
return dummy->next;
}
};


int main() {
// Write C++ code here
// std::cout << "Try programiz.pro";
Solution s= Solution();
// [4,2,1,3]
ListNode *a = new ListNode(4);
ListNode *b = new ListNode(2);
a->next = b;
ListNode *c =s.insertionSortList(a);
std::cout << "res: "<<c->val;
return 0;
}

0 comments on commit 9786836

Please sign in to comment.