Merge two sorted linked lists and return them as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:
Input: l1=1->2->4->NULL, l2=1->3->4->5->NULL
Output: 1->1->2->3->4->4->5->NULL
Approach
Java
public class MergeTwoSortedLinkList {public static void main(String[] args) {ListNode l1 = new ListNode(1);l1.next = new ListNode(2);l1.next.next = new ListNode(4);ListNode l2 = new ListNode(1);l2.next = new ListNode(3);l2.next.next = new ListNode(4);l2.next.next.next = new ListNode(5);ListNode head = mergeTwoLists(l1, l2);while(head!=null){System.out.print(" "+head.val);head=head.next;}}public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode r = null;boolean flag = true;ListNode head = null;while (l1 != null || l2 != null) {if (l1 != null && l2 != null && l1.val < l2.val) {if (flag) {head = l1;r = head;flag = false;} else {r.next = l1;r = l1;}l1 = l1.next;} else if (l1 != null && l2 != null && l1.val >= l2.val) {if (flag) {head = l2;r = head;flag = false;} else {r.next = l2;r = l2;}l2 = l2.next;} else if (l1 != null && l2 == null) {if (flag) {head = l1;r = head;flag = false;} else {r.next = l1;r = l1;}l1 = l1.next;} else {if (flag) {head = l2;r = head;flag = false;} else {r.next = l2;r = l2;}l2 = l2.next;}}return head;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}// Time Complexity : O(n)// Space Complexity : O(1)
C++
#include <bits/stdc++.h>using namespace std;//Structure of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//Function to merge two//Sorted LinklistNode* mergeTwoLinkLists(Node* l1, Node* l2){Node *temp1=l1,*temp2=l2;if(temp1==NULL && temp2==NULL)return NULL;if(temp1==NULL)return temp2;if(temp2==NULL)return temp1;Node *head=NULL,*temp=NULL;int flag=0;while(temp1&&temp2){if(temp1->data<temp2->data){if(flag==0){head=temp1;flag=1;temp=head;}else{temp->next=temp1;temp=temp1;}temp1=temp1->next;}else{if(flag==0){head=temp2;flag=1;temp=head;}else{temp->next=temp2;temp=temp2;}temp2=temp2->next;}}if(temp1)temp->next=temp1;else if(temp2)temp->next=temp2;return head;}int main(){Node *l1=new Node(1);l1->next=new Node(2);l1->next->next=new Node(4);Node *l2=new Node(1);l2->next=new Node(3);l2->next->next=new Node(4);l2->next->next->next=new Node(5);Node *head=mergeTwoLinkLists(l1,l2);while(head!=NULL){cout<<head->data<<" ";head=head->next;}return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment