How do I print out the data in my LinkedList - java

I have successflully created a LinkedList from scratch. So far it can only add data. No deletion or anything fancy like that.
I can add strings, integers etc but I have a problem with printing the data I have added. How do I do that? I guess I'll have to loop through it first, but how?'
Here is my Node class:
public class Node {
T data;
Node<T> nextNode;
public Node(T data) {
this.data = data;
}
public String toString () {
return data +"";
}
}
Here is the LinkedList class:
public class LinkedList <T> {
Node<T> head;
Node<T> tail;
public void add (T data) {
// where to add statements. if its empty or not
Node<T> node = new Node<T> (data);
if (tail == null) { // empty list
// nothng in the node = tail = node;
head = node;
tail = node;
}
else { // non empty list, add the new boogie train to the tail
tail.nextNode = node; // new node pointing to tail
tail = node; // update
}
}
And here is the main. Where I create an object out of Linkedlist and use the generic add method to add my data. But how do i print it out on the screen? Thanks in advance.
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<Object> ();
list.add(15); // boogie1 = head
list.add(16);
list.add(10); // boogie end = tail

Add a method toString to your LinkedList class
public String toString() {
Node<T> curr = head;
StringBuilder sb = new StringBuilder();
sb.append("LinkedList [");
while (curr != null) {
sb.append(curr.data);
if (curr.nextNode != null) {
sb.append(", ");
}
curr = curr.nextNode;
}
sb.append("]");
return sb.toString();
}
Then call it in your main method :
System.out.println(list.toString());

You have to override the toString() method in your LinkedList<T> class

Well, you can either implement the Iterator pattern: http://sourcemaking.com/design_patterns/iterator/java/1
Or you just implement a method that can either print the node element, or execute something on each of them, somewhat like this:
public class LinkedList <T> {
Node<T> head;
Node<T> tail;
public void add (T data) {
...
}
public void forEach(java.util.function.Consumer<T> consumer)
{
for(Node<T> currentNode = head; currentNode != null; currentNode = currentNode.nextNode)
//I am assuming the last node points to null in nextNode
// and that head is initialized to null if the list is empty
{
consumer.accept(currentNode);
}
}
}
Then just do
linkedList.forEach(x -> System.out.println(x.toString());
If everything is right, this should work in Java 8.

create a getter method in your LinkedList class.
public Node getHead() {
return head;
}
in your main()
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
list.add(15); // boogie1 = head
list.add(16);
list.add(10); // boogie end = tail
Node node = list.getHead();
// Break the loop after the variable reaches null, i.e. end of list.
// The un initialised instance non-primitive variable is always null by default.
while(node != null) {
System.out.println(node); // Calls the toString() from class Node.
node = node.nextNode; // Move to next node.
}
}
Hope this works for you.

Related

Implementing a method in the linkedList that returns the current node

I'm implementing a generic linkedList, but I had a hard time writing a function that returns the current node. It always returns the last added node. I'm sharing my code below.
I have searched for similar questions but I didn't find what I want.
Here's the linkedList file. I'm sure the add method which is vorne() is working as expected. It adds elements at the beginning.
public class Liste<T> {
// Points to the head of the Linked List
// i.e the first element
Node<T> head;
Node<T> tail;
static int size = 0;
static class Node<T> {
// Data Stored in each Node of the Linked List
T data;
// Pointer to the next node in the Linked List
Node<T> next;
// Node class constructor used to initializes the data
// in each Node
private Node(T data) {
this.data = data;
next = null;
}
}
public static <T> Liste<T> neu() {
Liste<T> l = new Liste<T>();
return l;
}
public static <T> Liste<T> einfuegen(Liste o, T auD, Nat nat) {
return null;
}
// Add element at the beginning
public static <T> Liste<T> vorne(Liste<T> list, T data) {
//Create new node
Node newNode = new Node(data);
//Checks if the list is empty.
if(list.head == null) {
//If list is empty, both head and tail would point to new node.
list.head = newNode;
list.tail = newNode;
newNode.next = list.head;
size++;
}
else {
//Store data into temporary node
Node temp = list.head;
//New node will point to temp as next node
newNode.next = temp;
//New node will be the head node
list.head = newNode;
//Since, it is circular linked list tail will point to head.
list.tail.next = list.head;
size++;
}
return list;
}
// This method should return the last added element
public static <T> T kopf(Liste<T> lNat) {
// Throws an Exception if the List is empty
if (lNat.head == null) {
System.out.print("No Element found");
}
return lNat.head.data;
}
// This method should return all the elements except the first element.
public static <T> Liste<T> rest(Liste<T> lString) {
// TODO Auto-generated method stub
if (lString.head != null) {
lString.head = lString.head.next;
}
return lString;
}
public int getCount() {
return size;
}
}
The problem arises here!
public static void main(String[] args) {
// TODO Auto-generated method stub
Liste<String> l0 = Liste.neu();
Liste<String> l1a = Liste.vorne(l0, "AuD");
Liste<String> l1b = Liste.vorne(l0, "PFP");
Liste<String> l2a = Liste.vorne(l1a, "FAUL");
Liste<String> l2b = Liste.vorne(l1b, "FAIL");
//Liste<String> l1x = Liste.rest(l2b);
//Liste<String> l1y = Liste.rest(l2b);
//Liste<String> l0x = Liste.rest(l1x);
//Liste<String> l0y = Liste.rest(l1y);
//String l0y = Liste.kopf(l2a);
System.out.println(l1b.getCount());
System.out.println(Liste.kopf(l2a));
}
The output:
4
FAIL
when I call the kopf method which supposes to return the last added element, it returns the string "FAIL" instead of "FAUL". I have stored it in a separate object, and I am calling l2a object, so why it's returning "FAIL". As you can see, I'm creating a new list using neu() method, then I'm using the same list to add elements. I think it's a silly bug that I don't see.
It seems I can't figure it out. Please any help would be appreciated.

Linked List adding elements at certain points

I'm trying to implement a LinkedList, the problem I'm having is adding elements to this list, I've already added elements in the main class and want to know how to add elements at the beginning of the list and at the end of the list. The current is able to print, but when i add new elements they cant be seen. I also want to know about getting the size of the linked list.
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
int size;
public void AddBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
this.size++;
head = newNode;
}
public void addAtEnd(int data) {
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
public void getSize() {
System.out.println(size);
}
public void printList(Node head) {
Node current = head;
while (current !=null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
Node head = new Node(25);
Node second = new Node(22);
Node third = new Node(7);
head.next = second;
second.next = third;
ll.AddBeginning(20);
ll.printList(head);
}
}
I would like to add 20 at the beginning and another integer at the end.
You are adding to Node 20 ll.AddBeginning(20); to LinkedList.head And Trying to print the list using Tester.head (declared in main method)
Solution:
Step 1 : Initialize LinkedList.head either
- Using constructor or
LinkedList ll = new LinkedList(head);
public LinkedList(Node head) {
this.head = head;
}
- Assign head to LinkedList object i.e., ll
ll.head = head; // Need to initialize Linked List with Head
Step 2 : No need to pass head variable to printList() function. It prints the LinkedList.head elements
ll.printList(); //Here you passing Tester.head not required
Code :
Tester main method
ll.head = head; // Need to initialize Linked List with Head
ll.AddBeginning(20); //Here actually adding node to linkedList head
ll.printList(); //Here you passing Tester.head not required
LinkedList.PrintList method
public void printList() {
Node current = this.head;//changed to linkedlist.head
while (current != null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}

How to duplicate every element of a linked list recursively in Java?

I have to write a duplicate function that duplicates every element of a linked list and returns a linked list such that if L = [2,3,4] then duplicate(L) = [2,2,3,3,4,4]. I have to do this recursively. I realize that below is not the correct solution, but I got confused. =(
public class MyList {
int value;
MyList next;
public static MyList duplicate(MyList L){
if(L.next == null){
L.next.value = L.value;
L.next.next = null;
} else {
MyList temp = L.next;
L.next.value = L.value;
L.next.next = temp;
duplicate(L.next);
}
return L;
}
}
First, check that L isn't an empty list (null). If it contains a value, return a new list that has that value repeated twice, followed by duplicating the rest of the list.
By giving MyList a constructor, this is more readable.
public class MyList {
int value;
MyList next;
public MyList(int value, MyList next) {
this.value = value;
this.next = next;
}
public static MyList duplicate(MyList list) {
if (list == null) {
return null;
} else {
return new MyList(list.value,
new MyList(list.value,
duplicate(list.next)));
}
}
}
You currently add an item and then call the recursion on it, ending at endlessly adding items.
You either need to at elements behind your recursion when processing in a forward-direction, or after the recursion when processing backwards.
Let's create a backwards-direction version. We first recursively walk to the end of the list and then resolve the recursion backwards, adding items after our current element each time.
public <E> void duplicateEntries(MyLinkedList<E> list) {
// Do nothing if list is empty
if (list.size() != 0) {
// Call the recursive method on the head node
duplicateEntriesHelper(list.head);
}
}
public <E> void duplicateEntriesHelper(Node<E> node) {
// Walk to the end of the list
if (node.next != null) {
duplicateEntriesHelper(node.next);
}
// Resolve recursion, duplicate current
// entry by inserting it after the current element
Node<E> duplicatedEntry = new Node<>();
duplicatedEntry.data = node.data;
// Insert element after current node
duplicatedEntry.next = node.next;
node.next = duplicatedEntry;
}
The classes I used should look similar to:
public class MyLinkedList<E> {
public Node<E> head = null;
#Override
public String toString() {
// Build something like "MyLinkedList[2, 3, 4]"
StringBuilder sb = new StringBuilder();
sb.append("MyLinkedList[");
StringJoiner sj = new StringJoiner(",");
Node<E> node = head;
while (node != null) {
sj.add(node);
node = node.next;
}
sb.append(sj);
sb.append("]");
return sb.toString();
}
}
public class Node<E> {
public Node next = null;
public E data = null;
#Override
public String toString() {
return E;
}
}
And here is the demo:
public static void main(String[] args) {
// Setup the list
MyLinkedList<Integer> list = new MyLinkedList<>();
Node<Integer> first = new Node<>();
first.data = 2;
Node<Integer> second = new Node<>();
second.data = 3;
Node<Integer> third = new Node<>();
third.data = 4;
list.head = data;
first.next = second;
second.next = third;
// Demonstrate the method
System.out.println("Before: " + list);
duplicateEntries(list);
System.out.println("After: " + list);
}
Of course you can add additional methods and functionality to them. For example using some constructors or getter/setter methods.

How to use compareTo() method to compare objects in a List?

I have a class called ListNode that works like a list. Using this class I want to establish a list of Magazine objects. In my MagazineList class I want to edit the add method so when I insert Magazines they will be sorted alphabetically. How can I do this?
My ListNode class:
public class ListNode {
private Object value;
private ListNode next;
//intializes node
public ListNode (Object initValue, ListNode initNext) {
value = initValue;
next = initNext;
}
//returns value of node
public Object getValue () {
return value;
}
//returns next reference of node
public ListNode getNext () {
return next;
}
//sets value of node
public void setValue (Object theNewValue) {
value = theNewValue;
}
//sets next reference of node
public void setNext (ListNode theNewNext) {
next = theNewNext;
}
}
my MagazineList class's add method:
//when instantiated, MagazineList's list variable is set to null
public void add (Magazine mag) {
ListNode node = new ListNode (mag, null);
ListNode current;
if (list == null)
list = node;
else {
current = list;
while (current.getNext() != null)
current = current.getNext();
current.setNext(node);
}
}
I used this method to compare the Magazines in the Magazine class:
//compares the names (Strings) of the Magazines.
public int compareTo(Magazine mag2) {
return (title).compareTo(mag2.toString());
}
One easy way to do this is to keep your list always sorted.
Then, each time you insert a new node, starting from the head, you should compare the the new node with each node in the list using compareTo method, and insert the new node after the node for which compareTo returns positive.
A basic implementation may be like this. You need to improve it and consider edge cases etc. though.
//when instantiated, MagazineList's list variable is set to null
public void add (Magazine mag) {
ListNode node = new ListNode (mag, null);
ListNode current;
if (list == null)
list = node;
else {
current = list; // you list head
while (node.compareTo(current) < 0)
current = current.getNext();
ListNode next = current.getNext();
current.setNext(node);
node.setNext(next);
}
}
Like this
//compares the names (Strings) of the Magazines.
public int compareTo(Magazine mag2) {
//assume that you have getTittle() method which returns Title
return title.compareTo(mag2.getTitle());
}

Reversing a linked list in Java, recursively

I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList, containing simple nodes called ListNode). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: public AddressList reverse()
ListNode:
public class ListNode{
public String data;
public ListNode next;
}
Right now my reverse function just calls a helper function that takes an argument to allow recursion.
public AddressList reverse(){
return new AddressList(this.reverse(this.head));
}
With my helper function having the signature of private ListNode reverse(ListNode current).
At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.
Edit: Nevermind, I figured it out in the meantime.
private AddressList reverse(ListNode current, AddressList reversedList){
if(current == null)
return reversedList;
reversedList.addToFront(current.getData());
return this.reverse(current.getNext(), reversedList);
}
While I'm here, does anyone see any problems with this route?
There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):
What is the reverse of null (the empty list)? null.
What is the reverse of a one element list? the element.
What is the reverse of an n element list? the reverse of the rest of the list followed by the first element.
public ListNode Reverse(ListNode list)
{
if (list == null) return null; // first question
if (list.next == null) return list; // second question
// third question - in Lisp this is easy, but we don't have cons
// so we grab the second element (which will be the last after we reverse it)
ListNode secondElem = list.next;
// bug fix - need to unlink list from the rest or you will get a cycle
list.next = null;
// then we reverse everything from the second element on
ListNode reverseRest = Reverse(secondElem);
// then we join the two lists
secondElem.next = list;
return reverseRest;
}
I was asked this question at an interview and was annoyed that I fumbled with it since I was a little nervous.
This should reverse a singly linked list, called with reverse(head,NULL);
so if this were your list:
1->2->3->4->5->null
it would become:
5->4->3->2->1->null
//Takes as parameters a node in a linked list, and p, the previous node in that list
//returns the head of the new list
Node reverse(Node n,Node p){
if(n==null) return null;
if(n.next==null){ //if this is the end of the list, then this is the new head
n.next=p;
return n;
}
Node r=reverse(n.next,n); //call reverse for the next node,
//using yourself as the previous node
n.next=p; //Set your next node to be the previous node
return r; //Return the head of the new list
}
edit: ive done like 6 edits on this, showing that it's still a little tricky for me lol
I got half way through (till null, and one node as suggested by plinth), but lost track after making recursive call. However, after reading the post by plinth, here is what I came up with:
Node reverse(Node head) {
// if head is null or only one node, it's reverse of itself.
if ( (head==null) || (head.next == null) ) return head;
// reverse the sub-list leaving the head node.
Node reverse = reverse(head.next);
// head.next still points to the last element of reversed sub-list.
// so move the head to end.
head.next.next = head;
// point last node to nil, (get rid of cycles)
head.next = null;
return reverse;
}
Here's yet another recursive solution. It has less code within the recursive function than some of the others, so it might be a little faster. This is C# but I believe Java would be very similar.
class Node<T>
{
Node<T> next;
public T data;
}
class LinkedList<T>
{
Node<T> head = null;
public void Reverse()
{
if (head != null)
head = RecursiveReverse(null, head);
}
private Node<T> RecursiveReverse(Node<T> prev, Node<T> curr)
{
Node<T> next = curr.next;
curr.next = prev;
return (next == null) ? curr : RecursiveReverse(curr, next);
}
}
The algo will need to work on the following model,
keep track of the head
Recurse till end of linklist
Reverse linkage
Structure:
Head
|
1-->2-->3-->4-->N-->null
null-->1-->2-->3-->4-->N<--null
null-->1-->2-->3-->4<--N<--null
null-->1-->2-->3<--4<--N<--null
null-->1-->2<--3<--4<--N<--null
null-->1<--2<--3<--4<--N<--null
null<--1<--2<--3<--4<--N
|
Head
Code:
public ListNode reverse(ListNode toBeNextNode, ListNode currentNode)
{
ListNode currentHead = currentNode; // keep track of the head
if ((currentNode==null ||currentNode.next==null )&& toBeNextNode ==null)return currentHead; // ignore for size 0 & 1
if (currentNode.next!=null)currentHead = reverse(currentNode, currentNode.next); // travarse till end recursively
currentNode.next = toBeNextNode; // reverse link
return currentHead;
}
Output:
head-->12345
head-->54321
I think this is more cleaner solution, which resembles LISP
// Example:
// reverse0(1->2->3, null) =>
// reverse0(2->3, 1) =>
// reverse0(3, 2->1) => reverse0(null, 3->2->1)
// once the first argument is null, return the second arg
// which is nothing but the reveresed list.
Link reverse0(Link f, Link n) {
if (f != null) {
Link t = new Link(f.data1, f.data2);
t.nextLink = n;
f = f.nextLink; // assuming first had n elements before,
// now it has (n-1) elements
reverse0(f, t);
}
return n;
}
I know this is an old post, but most of the answers are not tail recursive i.e. they do some operations after returning from the recursive call, and hence not the most efficient.
Here is a tail recursive version:
public Node reverse(Node previous, Node current) {
if(previous == null)
return null;
if(previous.equals(head))
previous.setNext(null);
if(current == null) { // end of list
head = previous;
return head;
} else {
Node temp = current.getNext();
current.setNext(previous);
reverse(current, temp);
}
return null; //should never reach here.
}
Call with:
Node newHead = reverse(head, head.getNext());
void reverse(node1,node2){
if(node1.next!=null)
reverse(node1.next,node1);
node1.next=node2;
}
call this method as reverse(start,null);
public Node reverseListRecursive(Node curr)
{
if(curr == null){//Base case
return head;
}
else{
(reverseListRecursive(curr.next)).next = (curr);
}
return curr;
}
public void reverse() {
head = reverseNodes(null, head);
}
private Node reverseNodes(Node prevNode, Node currentNode) {
if (currentNode == null)
return prevNode;
Node nextNode = currentNode.next;
currentNode.next = prevNode;
return reverseNodes(currentNode, nextNode);
}
Reverse by recursive algo.
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) return head;
ListNode rHead = reverse(head.next);
rHead.next = head;
head = null;
return rHead;
}
By iterative
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null;
ListNode cur = head
ListNode next = head.next;
while (next != null) {
cur.next = prev;
prev = cur;
cur = next;
next = next.next;
}
return cur;
}
public static ListNode recRev(ListNode curr){
if(curr.next == null){
return curr;
}
ListNode head = recRev(curr.next);
curr.next.next = curr;
curr.next = null;
// propogate the head value
return head;
}
This solution demonstrates that no arguments are required.
/**
* Reverse the list
* #return reference to the new list head
*/
public LinkNode reverse() {
if (next == null) {
return this; // Return the old tail of the list as the new head
}
LinkNode oldTail = next.reverse(); // Recurse to find the old tail
next.next = this; // The old next node now points back to this node
next = null; // Make sure old head has no next
return oldTail; // Return the old tail all the way back to the top
}
Here is the supporting code, to demonstrate that this works:
public class LinkNode {
private char name;
private LinkNode next;
/**
* Return a linked list of nodes, whose names are characters from the given string
* #param str node names
*/
public LinkNode(String str) {
if ((str == null) || (str.length() == 0)) {
throw new IllegalArgumentException("LinkNode constructor arg: " + str);
}
name = str.charAt(0);
if (str.length() > 1) {
next = new LinkNode(str.substring(1));
}
}
public String toString() {
return name + ((next == null) ? "" : next.toString());
}
public static void main(String[] args) {
LinkNode head = new LinkNode("abc");
System.out.println(head);
System.out.println(head.reverse());
}
}
Here is a simple iterative approach:
public static Node reverse(Node root) {
if (root == null || root.next == null) {
return root;
}
Node curr, prev, next;
curr = root; prev = next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
And here is a recursive approach:
public static Node reverseR(Node node) {
if (node == null || node.next == null) {
return node;
}
Node next = node.next;
node.next = null;
Node remaining = reverseR(next);
next.next = node;
return remaining;
}
As Java is always pass-by-value, to recursively reverse a linked list in Java, make sure to return the "new head"(the head node after reversion) at the end of the recursion.
static ListNode reverseR(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode first = head;
ListNode rest = head.next;
// reverse the rest of the list recursively
head = reverseR(rest);
// fix the first node after recursion
first.next.next = first;
first.next = null;
return head;
}
PointZeroTwo has got elegant answer & the same in Java ...
public void reverseList(){
if(head!=null){
head = reverseListNodes(null , head);
}
}
private Node reverseListNodes(Node parent , Node child ){
Node next = child.next;
child.next = parent;
return (next==null)?child:reverseListNodes(child, next);
}
public class Singlelinkedlist {
public static void main(String[] args) {
Elem list = new Elem();
Reverse(list); //list is populate some where or some how
}
//this is the part you should be concerned with the function/Method has only 3 lines
public static void Reverse(Elem e){
if (e!=null)
if(e.next !=null )
Reverse(e.next);
//System.out.println(e.data);
}
}
class Elem {
public Elem next; // Link to next element in the list.
public String data; // Reference to the data.
}
public Node reverseRec(Node prev, Node curr) {
if (curr == null) return null;
if (curr.next == null) {
curr.next = prev;
return curr;
} else {
Node temp = curr.next;
curr.next = prev;
return reverseRec(curr, temp);
}
}
call using: head = reverseRec(null, head);
What other guys done , in other post is a game of content, what i did is a game of linkedlist, it reverse the LinkedList's member not reverse of a Value of members.
Public LinkedList reverse(LinkedList List)
{
if(List == null)
return null;
if(List.next() == null)
return List;
LinkedList temp = this.reverse( List.next() );
return temp.setNext( List );
}
package com.mypackage;
class list{
node first;
node last;
list(){
first=null;
last=null;
}
/*returns true if first is null*/
public boolean isEmpty(){
return first==null;
}
/*Method for insertion*/
public void insert(int value){
if(isEmpty()){
first=last=new node(value);
last.next=null;
}
else{
node temp=new node(value);
last.next=temp;
last=temp;
last.next=null;
}
}
/*simple traversal from beginning*/
public void traverse(){
node t=first;
while(!isEmpty() && t!=null){
t.printval();
t= t.next;
}
}
/*static method for creating a reversed linked list*/
public static void reverse(node n,list l1){
if(n.next!=null)
reverse(n.next,l1);/*will traverse to the very end*/
l1.insert(n.value);/*every stack frame will do insertion now*/
}
/*private inner class node*/
private class node{
int value;
node next;
node(int value){
this.value=value;
}
void printval(){
System.out.print(value+" ");
}
}
}
The solution is:
package basic;
import custom.ds.nodes.Node;
public class RevLinkedList {
private static Node<Integer> first = null;
public static void main(String[] args) {
Node<Integer> f = new Node<Integer>();
Node<Integer> s = new Node<Integer>();
Node<Integer> t = new Node<Integer>();
Node<Integer> fo = new Node<Integer>();
f.setNext(s);
s.setNext(t);
t.setNext(fo);
fo.setNext(null);
f.setItem(1);
s.setItem(2);
t.setItem(3);
fo.setItem(4);
Node<Integer> curr = f;
display(curr);
revLL(null, f);
display(first);
}
public static void display(Node<Integer> curr) {
while (curr.getNext() != null) {
System.out.println(curr.getItem());
System.out.println(curr.getNext());
curr = curr.getNext();
}
}
public static void revLL(Node<Integer> pn, Node<Integer> cn) {
while (cn.getNext() != null) {
revLL(cn, cn.getNext());
break;
}
if (cn.getNext() == null) {
first = cn;
}
cn.setNext(pn);
}
}
static void reverseList(){
if(head!=null||head.next!=null){
ListNode tail=head;//head points to tail
ListNode Second=head.next;
ListNode Third=Second.next;
tail.next=null;//tail previous head is poiniting null
Second.next=tail;
ListNode current=Third;
ListNode prev=Second;
if(Third.next!=null){
while(current!=null){
ListNode next=current.next;
current.next=prev;
prev=current;
current=next;
}
}
head=prev;//new head
}
}
class ListNode{
public int data;
public ListNode next;
public int getData() {
return data;
}
public ListNode(int data) {
super();
this.data = data;
this.next=null;
}
public ListNode(int data, ListNode next) {
super();
this.data = data;
this.next = next;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
private Node ReverseList(Node current, Node previous)
{
if (current == null) return null;
Node originalNext = current.next;
current.next = previous;
if (originalNext == null) return current;
return ReverseList(originalNext, current);
}
//this function reverses the linked list
public Node reverseList(Node p) {
if(head == null){
return null;
}
//make the last node as head
if(p.next == null){
head.next = null;
head = p;
return p;
}
//traverse to the last node, then reverse the pointers by assigning the 2nd last node to last node and so on..
return reverseList(p.next).next = p;
}
//Recursive solution
class SLL
{
int data;
SLL next;
}
SLL reverse(SLL head)
{
//base case - 0 or 1 elements
if(head == null || head.next == null) return head;
SLL temp = reverse(head.next);
head.next.next = head;
head.next = null;
return temp;
}
Inspired by an article discussing immutable implementations of recursive data structures I put an alternate solution together using Swift.
The leading answer documents solution by highlighting the following topics:
What is the reverse of nil (the empty list)?
Does not matter here, because we have nil protection in Swift.
What is the reverse of a one element list?
The element itself
What is the reverse of an n element list?
The reverse of the second element on followed by the first element.
I have called these out where applicable in the solution below.
/**
Node is a class that stores an arbitrary value of generic type T
and a pointer to another Node of the same time. This is a recursive
data structure representative of a member of a unidirectional linked
list.
*/
public class Node<T> {
public let value: T
public let next: Node<T>?
public init(value: T, next: Node<T>?) {
self.value = value
self.next = next
}
public func reversedList() -> Node<T> {
if let next = self.next {
// 3. The reverse of the second element on followed by the first element.
return next.reversedList() + value
} else {
// 2. Reverse of a one element list is itself
return self
}
}
}
/**
#return Returns a newly created Node consisting of the lhs list appended with rhs value.
*/
public func +<T>(lhs: Node<T>, rhs: T) -> Node<T> {
let tail: Node<T>?
if let next = lhs.next {
// The new tail is created recursively, as long as there is a next node.
tail = next + rhs
} else {
// If there is not a next node, create a new tail node to append
tail = Node<T>(value: rhs, next: nil)
}
// Return a newly created Node consisting of the lhs list appended with rhs value.
return Node<T>(value: lhs.value, next: tail)
}
Reversing the linked list using recursion. The idea is adjusting the links by reversing the links.
public ListNode reverseR(ListNode p) {
//Base condition, Once you reach the last node,return p
if (p == null || p.next == null) {
return p;
}
//Go on making the recursive call till reach the last node,now head points to the last node
ListNode head = reverseR(p.next); //Head points to the last node
//Here, p points to the last but one node(previous node), q points to the last node. Then next next step is to adjust the links
ListNode q = p.next;
//Last node link points to the P (last but one node)
q.next = p;
//Set the last but node (previous node) next to null
p.next = null;
return head; //Head points to the last node
}
public void reverseLinkedList(Node node){
if(node==null){
return;
}
reverseLinkedList(node.next);
Node temp = node.next;
node.next=node.prev;
node.prev=temp;
return;
}
public void reverse(){
if(isEmpty()){
return;
}
Node<T> revHead = new Node<T>();
this.reverse(head.next, revHead);
this.head = revHead;
}
private Node<T> reverse(Node<T> node, Node<T> revHead){
if(node.next == null){
revHead.next = node;
return node;
}
Node<T> reverse = this.reverse(node.next, revHead);
reverse.next = node;
node.next = null;
return node;
}
Here is a reference if someone is looking for Scala implementation:
scala> import scala.collection.mutable.LinkedList
import scala.collection.mutable.LinkedList
scala> def reverseLinkedList[A](ll: LinkedList[A]): LinkedList[A] =
ll.foldLeft(LinkedList.empty[A])((accumulator, nextElement) => nextElement +: accumulator)
reverseLinkedList: [A](ll: scala.collection.mutable.LinkedList[A])scala.collection.mutable.LinkedList[A]
scala> reverseLinkedList(LinkedList("a", "b", "c"))
res0: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(c, b, a)
scala> reverseLinkedList(LinkedList("1", "2", "3"))
res1: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(3, 2, 1)

Categories

Resources