https://leetcode.com/problems/merge-two-sorted-lists/submissions/ soultion in both c++ and JavaScript easy question if you know linked list
Merge two linked list solution in c++
--------------------------------------------------------------------------------------------------------------------
c++
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
/**
* Definition for singly-linked list.
* 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* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode *tempNode=new ListNode(); //create a new node
ListNode *head=tempNode; //create a new head and assign new node to head
while(list1 && list2) //until list1 or list2 not null
{
if(list1->val<list2->val)
{
tempNode->next=list1; //list one node value
list1=list1->next;
}else
{
tempNode->next=list2;//list two node value
list2=list2->next;
}
tempNode=tempNode->next;
}
if(list1!=nullptr)
{
tempNode->next=list1;
}else
{
tempNode->next=list2;
}
return head->next;
}
};
//also other solution in JavaScript which does not seems to be good one
-------------------------------------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
var arr=[];
let currentNode=l1;
while(currentNode!=null)
{
arr.push(currentNode.val);
currentNode=currentNode.next;
}
currentNode=l2;
while(currentNode!=null)
{
arr.push(currentNode.val);
currentNode=currentNode.next;
}
arr.sort((a,b)=>{ return a-b});
let head=null;
let tail=null;
for(let i=0;i<arr.length;i++)
{
let node=new ListNode(arr[i]);
if(head==null)
{
head=node;
tail=node;
}else
{
tail.next=node;
tail=node;
}
}
return head;
};
Comments
Post a Comment