Given a linked list, swap every two adjacent nodes and return its head.
Write a program to Swap Nodes in Pairs.
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Approach
Java
public class SwapLinkListPair {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);ListNode node = swapPairs(l);while (node != null) {System.out.print(" " + node.val);node = node.next;}}public static ListNode swapPairs(ListNode head) {if (head == null)return head;ListNode c = head;ListNode n = c.next;if (n == null)return head;while (n != null) {if (n != null) {int val = c.val;c.val = n.val;n.val = val;c = n.next;if (c != null) {n = c.next;} elsen = null;}}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;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//Function to swap nodes in pair in//linklistNode *swapPairs(Node *head){if(head==NULL||head->next==NULL)return head;Node *temp=head;while(temp!=NULL){if(temp->next!=NULL){int val=temp->data;temp->data=temp->next->data;temp->next->data=val;temp=temp->next;}temp=temp->next;}return head;}int main(){Node *head=new Node(1);head->next=new Node(2);head->next->next=new Node(3);head->next->next->next=new Node(4);head=swapPairs(head);Node *temp=head;cout<<"New List is\n";while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment