Created
July 9, 2018 14:44
-
-
Save RameshRM/48d1e0518eebf0b2fec15a87bbd1a062 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LinkedList { | |
private Node head; | |
private Node current; | |
private boolean isFirst = false; | |
private int length; | |
public LinkedList() { | |
} | |
public LinkedList(Node head) { | |
this.head = head; | |
} | |
public Node reverse(Node headElement, int k) { | |
Node current = headElement; | |
Node previous = null; | |
Node next = null; | |
int count = 0; | |
while (current != null && count < k) { | |
next = current.getNext(); | |
current.setNext(previous); | |
previous = current; | |
current = next; | |
count++; | |
} | |
if (null != next && this.length - count > k) { | |
headElement.setNext(reverse(next, k)); | |
}else{ | |
Node tail = previous; | |
while(tail != null){ | |
if(tail.getNext() !=null){ | |
tail = tail.getNext(); | |
}else{ | |
break; | |
} | |
} | |
tail.setNext(current); | |
} | |
return previous; | |
} | |
public Node reverse() { | |
Node current = head; | |
Node previous = null; | |
Node next = null; | |
while (current != null) { | |
next = current.getNext(); | |
current.setNext(previous); | |
previous = current; | |
current = next; | |
} | |
head = previous; | |
return previous; | |
} | |
public void add(int data) { | |
this.length++; | |
boolean isStart = false; | |
if (null == head) { | |
isStart = true; | |
head = new Node(data); | |
} | |
Node n = new Node(data); | |
if (null == current && !isStart) { | |
head.setNext(n); | |
current = n; | |
isFirst = false; | |
return; | |
} | |
if (null != current) { | |
while (current.getNext() != null) { | |
current = current.getNext(); | |
} | |
current.setNext(n); | |
} | |
} | |
public void display() { | |
Node current = head; | |
while (current != null) { | |
System.out.print(String.format("%s ->", current.getData())); | |
current = current.getNext(); | |
} | |
System.out.println("-----"); | |
} | |
public static void main(String[] args) { | |
LinkedList linkedList = new LinkedList(); | |
linkedList.add(1); | |
linkedList.add(2); | |
// linkedList.add(3); | |
// linkedList.add(4); | |
// linkedList.add(5); | |
linkedList.display(); | |
linkedList.reverse(); | |
// linkedList.head = linkedList.reverse(linkedList.head, 3); | |
linkedList.display(); | |
} | |
} | |
class Node { | |
private final int data; | |
public void setNext(Node next) { | |
this.next = next; | |
} | |
public int getData() { | |
return data; | |
} | |
public Node getNext() { | |
return next; | |
} | |
private Node next = null; | |
public Node(int data) { | |
this.data = data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment