Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class Node
- {
- int data;
- Node next;
- Node(int d) {data = d; next = null; }
- }
- class insertion
- {
- Node head;
- Node tail;
- public void addToTheLast(Node node)
- {
- if (head == null)
- {
- head = node;
- tail = node;
- }
- else
- {
- tail.next = node;
- tail = node;
- }
- }
- void printList(Node head)
- {
- Node temp = head;
- while (temp != null)
- {
- System.out.print(temp.data + " ");
- temp = temp.next;
- }
- System.out.println();
- }
- /* Drier program to test above functions */
- }
- class Main
- {
- public static void main(String args[])throws IOException
- {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String S[] = br.readLine().split(" ");
- int N = Integer.parseInt(S[0]);
- int m = Integer.parseInt(S[1]);
- int n = Integer.parseInt(S[2]);
- String S1[] = br.readLine().split(" ");
- insertion llist = new insertion();
- int a1 = Integer.parseInt(S1[0]);
- Node head = new Node(a1);
- llist.addToTheLast(head);
- for (int i = 1; i < N; i++)
- {
- int a = Integer.parseInt(S1[i]);
- llist.addToTheLast(new Node(a));
- }
- Solution ob = new Solution();
- Node newhead = ob.reverseBetween(llist.head, m, n);
- llist.printList(newhead);
- }
- }
- class Solution
- {
- public static Node reverse(Node head) {
- Node prev = null;
- Node curr = head;
- Node next = head.next;
- while (curr != null) {
- next = curr.next;
- curr.next = prev;
- prev = curr;
- curr = next;
- }
- return prev;
- }
- public static Node reverseBetween(Node head, int m, int n)
- {
- if (m == n)
- return head;
- Node ret = new Node(0);
- ret.next = head;
- Node l = ret;
- for (int i = 0; i < n; i++) {
- if (i+1 == m) {
- // a= 2
- Node a=head;
- Node prev=null;
- Node curr = head;
- Node next = head.next;
- while (i!=n) {
- i++;
- next = curr.next;
- curr.next = prev;
- prev = curr;
- curr = next;
- }
- l.next=prev;
- a.next=next;
- return ret.next;
- }
- l = head;
- head = head.next;
- }
- return ret.next;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement