Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
Example:
Input: 1->2->3->4->5->NULL, k=3
Output: 3->2->1->4->5->NULL
Approach
Java
public class ReverseNodesKGroup {public static void main(String[] args) {ListNode head = new ListNode(1);head.next = new ListNode(2);head.next.next = new ListNode(3);head.next.next.next = new ListNode(4);head.next.next.next.next = new ListNode(5);int k = 3;head = reverseKGroup(head, k);linkedListTraversal(head);}static ListNode reverseKGroup(ListNode head, int k) {ListNode curr = head;ListNode next = null;ListNode prev = null;int count = 0;ListNode temp = head;int cnt = 0;// Checking if number of ListNodes is a multiple of k or notwhile (temp != null) {temp = temp.next;cnt++;}// if not multiple of k then left the remaining ListNodesif (cnt < k) {return head;}// Reverse first k ListNodeswhile (curr != null && count < k) {next = curr.next;curr.next = prev;prev = curr;curr = next;count++;}if (next != null) {head.next = reverseKGroup(next, k);}return prev;}private static void linkedListTraversal(ListNode ListNode) {while (ListNode != null) {System.out.print(ListNode.val + " ");ListNode = ListNode.next;}}}class ListNode{int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
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;}};Node *reverseKGroup(Node *head, int k){Node *curr = head;Node *next = NULL;Node *prev = NULL;int count = 0;Node *temp = head;int cnt = 0;// Checking if number of nodes is a multiple of k or notwhile (temp != NULL){temp = temp->next;cnt++;}// if not multiple of k then left the remaining nodesif (cnt < k){return head;}//Reverse first k nodeswhile (curr != NULL && count < k){next = curr->next;curr->next = prev;prev = curr;curr = next;count++;}if (next != NULL){head->next = reverseKGroup(next, k);}return prev;}void printLinkedList(Node *head){Node *temp = head;if (head == NULL)return;while (temp != NULL){cout << temp->data;temp = temp->next;if (temp != NULL)cout << "->";}}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->next->next->next->next = new Node(5);int k = 3;head = reverseKGroup(head, k);printLinkedList(head);return 0;}
No comments:
Post a Comment