This question already has answers here:
How to reverse a singly-linked list in blocks of some given size in O(n) time in place?
(4 answers)
Closed 4 years ago.
Can someone tell me why my code dosent work? I want to reverse a single linked list in java: This is the method (that doesnt work correctly)
public void reverseList(){
Node before = null;
Node tmp = head;
Node next = tmp.next;
while(tmp != null){
if(next == null)
return;
tmp.next = before;
before = tmp;
tmp = next;
next = next.next;
}
}
And this is the Node class:
public class Node{
public int data;
public Node next;
public Node(int data, Node next){
this.data = data;
this.next = next;
}
}
On input 4->3->2->1 I got output 4. I debugged it and it sets pointers correctly but still I dont get why it outputs only 4.
Node next = tmp.next;
while(tmp != null){
So what happens when tmp == null?
You almost got it, though.
Node before = null;
Node tmp = head;
while (tmp != null) {
Node next = tmp.next;
tmp.next = before;
before = tmp;
tmp = next;
}
head = before;
Or in nicer (?) naming:
Node reversedPart = null;
Node current = head;
while (current != null) {
Node next = current.next;
current.next = reversedPart;
reversedPart = current;
current = next;
}
head = reversedPart;
ASCII art:
<__<__<__ __ : reversedPart : head
(__)__ __ __
head : current: > > >
public Node<E> reverseList(Node<E> node) {
if (node == null || node.next == null) {
return node;
}
Node<E> currentNode = node;
Node<E> previousNode = null;
Node<E> nextNode = null;
while (currentNode != null) {
nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
}
The method for reversing a linked list is as below;
Reverse Method
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next; // store incoming item
curr.next = pre; // swap nodes
pre = curr; // increment also pre
curr = incoming; // increment current
}
head = pre; // pre is the latest item where
// curr is null
}
Three references are needed to reverse a list: pre, curr, incoming
... pre curr incoming
... --> (n-1) --> (n) --> (n+1) --> ...
To reverse a node, you have to store previous element, so that you can use the simple stament;
curr.next = pre;
To reverse the current element's direction. However, to iterate over the list, you have to store incoming element before the execution of the statement above because as reversing the current element's next reference, you don't know the incoming element anymore, that's why a third reference needed.
The demo code is as below;
LinkedList Sample Class
public class LinkedList<E> {
protected Node<E> head;
public LinkedList() {
head = null;
}
public LinkedList(E[] list) {
this();
addAll(list);
}
public void addAll(E[] list) {
for(int i = 0; i < list.length; i++)
add(list[i]);
}
public void add(E e) {
if(head == null)
head = new Node<E>(e);
else {
Node<E> temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = new Node<E>(e);
}
}
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next; // store incoming item
curr.next = pre; // swap nodes
pre = curr; // increment also pre
curr = incoming; // increment current
}
head = pre; // pre is the latest item where
// curr is null
}
public void printList() {
Node<E> temp = head;
System.out.print("List: ");
while(temp != null) {
System.out.print(temp + " ");
temp = temp.next;
}
System.out.println();
}
public static class Node<E> {
protected E e;
protected Node<E> next;
public Node(E e) {
this.e = e;
this.next = null;
}
#Override
public String toString() {
return e.toString();
}
}
}
Test Code
public class ReverseLinkedList {
public static void main(String[] args) {
Integer[] list = { 4, 3, 2, 1 };
LinkedList<Integer> linkedList = new LinkedList<Integer>(list);
linkedList.printList();
linkedList.reverseList();
linkedList.printList();
}
}
Output
List: 4 3 2 1
List: 1 2 3 4
If this isn't homework and you are doing this "manually" on purpose, then I would recommend using
Collections.reverse(list);
Collections.reverse() returns void, and your list is reversed after the call.
We can have three nodes previous,current and next.
public void reverseLinkedlist()
{
/*
* Have three nodes i.e previousNode,currentNode and nextNode
When currentNode is starting node, then previousNode will be null
Assign currentNode.next to previousNode to reverse the link.
In each iteration move currentNode and previousNode by 1 node.
*/
Node previousNode = null;
Node currentNode = head;
while (currentNode != null)
{
Node nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
head = previousNode;
}
public void reverse() {
Node prev = null; Node current = head; Node next = current.next;
while(current.next != null) {
current.next = prev;
prev = current;
current = next;
next = current.next;
}
current.next = prev;
head = current;
}
// Java program for reversing the linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// Function to reverse the linked list
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}
OUTPUT: -
Given Linked list
85 15 4 20
Reversed linked list
20 4 15 85
I know the recursive solution is not the optimal one, but just wanted to add one here:
public class LinkedListDemo {
static class Node {
int val;
Node next;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
#Override
public String toString() {
return "" + val;
}
}
public static void main(String[] args) {
Node n = new Node(1, new Node(2, new Node(3, new Node(20, null))));
display(n);
n = reverse(n);
display(n);
}
static Node reverse(Node n) {
Node tail = n;
while (tail.next != null) {
tail = tail.next;
}
reverseHelper(n);
return (tail);
}
static Node reverseHelper(Node n) {
if (n.next != null) {
Node reverse = reverseHelper(n.next);
reverse.next = n;
n.next = null;
return (n);
}
return (n);
}
static void display(Node n) {
for (; n != null; n = n.next) {
System.out.println(n);
}
}
}
I don't get it... why not doing this :
private LinkedList reverseLinkedList(LinkedList originalList){
LinkedList reversedList = new LinkedList<>();
for(int i=0 ; i<originalList.size() ; i++){
reversedList.add(0, originalList.get(i));
}
return reversedList;
}
I find this easier.
A more elegant solution would be to use recursion
void ReverseList(ListNode current, ListNode previous) {
if(current.Next != null)
{
ReverseList(current.Next, current);
ListNode temp = current.Next;
temp.Next = current;
current.Next = previous;
}
}
I tried the below code and it works fine:
Node head = firstNode;
Node current = head;
while(current != null && current.next != null){
Node temp = current.next;
current.next = temp.next;
temp.next = head;
head = temp;
}
Basically one by one it sets the next pointer of one node to its next to next node, so from next onwards all nodes are attached at the back of the list.
Node reverse_rec(Node start) {
if (start == null || start -> next == null) {
return start;
}
Node new_start = reverse(start->next);
start->next->next = start;
start->next = null;
return new_start;
}
Node reverse(Node start) {
Node cur = start;
Node bef = null;
while (cur != null) {
Node nex = cur.next;
cur.next = bef;
bef = cur;
cur = nex;
}
return bef;
}
I think your problem is that your initially last element next attribute isn't being changed becuase of your condition
if(next == null)
return;
Is at the beginning of your loop.
I would move it right after tmp.next has been assigned:
while(tmp != null){
tmp.next = before;
if(next == null)
return;
before = tmp;
tmp = next;
next = next.next;
}
Use this.
if (current== null || current.next==null) return current;
Node nextItem = current.next;
current.next = null;
Node reverseRest = reverse(nextItem);
nextItem.next = current;
return reverseRest
or Java Program to reverse a Singly Linked List
package com.three;
public class Link {
int a;
Link Next;
public Link(int i){
a=i;
}
}
public class LinkList {
Link First = null;
public void insertFirst(int a){
Link objLink = new Link(a);
objLink.Next=First;
First = objLink;
}
public void displayLink(){
Link current = First;
while(current!=null){
System.out.println(current.a);
current = current.Next;
}
}
public void ReverseLink(){
Link current = First;
Link Previous = null;
Link temp = null;
while(current!=null){
if(current==First)
temp = current.Next;
else
temp=current.Next;
if(temp==null){
First = current;
//return;
}
current.Next=Previous;
Previous=current;
//System.out.println(Previous);
current = temp;
}
}
public static void main(String args[]){
LinkList objLinkList = new LinkList();
objLinkList.insertFirst(1);
objLinkList.insertFirst(2);
objLinkList.insertFirst(3);
objLinkList.insertFirst(4);
objLinkList.insertFirst(5);
objLinkList.insertFirst(6);
objLinkList.insertFirst(7);
objLinkList.insertFirst(8);
objLinkList.displayLink();
System.out.println("-----------------------------");
objLinkList.ReverseLink();
objLinkList.displayLink();
}
}
You can also try this
LinkedListNode pointer = head;
LinkedListNode prev = null, curr = null;
/* Pointer variable loops through the LL */
while(pointer != null)
{
/* Proceed the pointer variable. Before that, store the current pointer. */
curr = pointer; //
pointer = pointer.next;
/* Reverse the link */
curr.next = prev;
/* Current becomes previous for the next iteration */
prev = curr;
}
System.out.println(prev.printForward());
package LinkedList;
import java.util.LinkedList;
public class LinkedListNode {
private int value;
private LinkedListNode next = null;
public LinkedListNode(int i) {
this.value = i;
}
public LinkedListNode addNode(int i) {
this.next = new LinkedListNode(i);
return next;
}
public LinkedListNode getNext() {
return next;
}
#Override
public String toString() {
String restElement = value+"->";
LinkedListNode newNext = getNext();
while(newNext != null)
{restElement = restElement + newNext.value + "->";
newNext = newNext.getNext();}
restElement = restElement +newNext;
return restElement;
}
public static void main(String[] args) {
LinkedListNode headnode = new LinkedListNode(1);
headnode.addNode(2).addNode(3).addNode(4).addNode(5).addNode(6);
System.out.println(headnode);
headnode = reverse(null,headnode,headnode.getNext());
System.out.println(headnode);
}
private static LinkedListNode reverse(LinkedListNode prev, LinkedListNode current, LinkedListNode next) {
current.setNext(prev);
if(next == null)
return current;
return reverse(current,next,next.getNext());
}
private void setNext(LinkedListNode prev) {
this.next = prev;
}
}
public class ReverseLinkedList {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("a");
linkedList.add("b");
linkedList.add("c");
linkedList.add("d");
linkedList.add("e");
linkedList.add("f");
System.out.println("Original linkedList:");
for(int i = 0; i <=linkedList.size()-1; i++){
System.out.println(" - "+ linkedList.get(i));
}
LinkedList<String> reversedlinkedList = reverse(linkedList);
System.out.println("Reversed linkedList:");
for(int i = 0; i <=reversedlinkedList.size()-1; i++){
System.out.println(" - "+ reversedlinkedList.get(i));
}
}
public static LinkedList<String> reverse(LinkedList<String> linkedList){
for(int i = 0; i < linkedList.size()/2; i++){
String temp = linkedList.get(i);
linkedList.set(i, linkedList.get(linkedList.size()-1-i));
linkedList.set((linkedList.size()-1-i), temp);
}
return linkedList;
}
}
To reverse a singly linked list you should have three nodes, top, beforeTop and AfterTop. Top is the header of singly linked list, hence beforeTop would be null and afterTop would be next element of top and with each iteration move forward beforeTop is assigned top and top is assigned afterTop(i.e. top.next).
private static Node inverse(Node top) {
Node beforeTop=null, afterTop;
while(top!=null){
afterTop=top.next;
top.next=beforeTop;
beforeTop=top;
top=afterTop;
}
return beforeTop;
}
Using Recursion It's too easy :
package com.config;
import java.util.Scanner;
public class Help {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Node head = null;
Node temp = null;
int choice = 0;
boolean flage = true;
do{
Node node = new Node();
System.out.println("Enter Node");
node.data = sc.nextInt();
if(flage){
head = node;
flage = false;
}
if(temp!=null)
temp.next = node;
temp = node;
System.out.println("Enter 0 to exit.");
choice = sc.nextInt();
}while(choice!=0);
Help.getAll(head);
Node reverse = Help.reverse(head,null);
//reverse = Help.reverse(head, null);
Help.getAll(reverse);
}
public static void getAll(Node head){
if(head==null)
return ;
System.out.println(head.data+"Memory Add "+head.hashCode());
getAll(head.next);
}
public static Node reverse(Node head,Node tail){
Node next = head.next;
head.next = tail;
return (next!=null? reverse(next,head) : head);
}
}
class Node{
int data = 0;
Node next = null;
}
Node Reverse(Node head) {
Node n,rev;
rev = new Node();
rev.data = head.data;
rev.next = null;
while(head.next != null){
n = new Node();
head = head.next;
n.data = head.data;
n.next = rev;
rev = n;
n=null;
}
return rev;
}
Use above function to reverse single linked list.
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
check more details about complexity analysis
http://javamicro.com/ref-card/DS-Algo/How-to-Reverse-Singly-Linked-List?
public static LinkedList reverseLinkedList(LinkedList node) {
if (node == null || node.getNext() == null) {
return node;
}
LinkedList remaining = reverseLinkedList(node.getNext());
node.getNext().setNext(node);
node.setNext(null);
return remaining;
}
/**
* Reverse LinkedList
* #author asharda
*
*/
class Node
{
int data;
Node next;
Node(int data)
{
this.data=data;
}
}
public class ReverseLinkedList {
static Node root;
Node temp=null;
public void insert(int data)
{
if(root==null)
{
root=new Node(data);
}
else
{
temp=root;
while(temp.next!=null)
{
temp=temp.next;
}
Node newNode=new Node(data);
temp.next=newNode;
}
}//end of insert
public void display(Node head)
{
while(head!=null)
{
System.out.println(head.data);
head=head.next;
}
}
public Node reverseLinkedList(Node head)
{
Node newNode;
Node tempr=null;
while(head!=null)
{
newNode=new Node(head.data);
newNode.next=tempr;
tempr=newNode;
head=head.next;
}
return tempr;
}
public static void main(String[] args) {
ReverseLinkedList r=new ReverseLinkedList();
r.insert(10);
r.insert(20);
r.insert(30);
r.display(root);
Node t=r.reverseLinkedList(root);
r.display(t);
}
}
public class SinglyLinkedListImpl<T> {
private Node<T> head;
public void add(T element) {
Node<T> item = new Node<T>(element);
if (head == null) {
head = item;
} else {
Node<T> temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = item;
}
}
private void reverse() {
Node<T> temp = null;
Node<T> next = null;
while (head != null) {
next = head.next;
head.next = temp;
temp = head;
head = next;
}
head = temp;
}
void printList(Node<T> node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String a[]) {
SinglyLinkedListImpl<Integer> sl = new SinglyLinkedListImpl<Integer>();
sl.add(1);
sl.add(2);
sl.add(3);
sl.add(4);
sl.printList(sl.head);
sl.reverse();
sl.printList(sl.head);
}
static class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
super();
this.data = data;
}
}
}
public class Linkedtest {
public static void reverse(List<Object> list) {
int lenght = list.size();
for (int i = 0; i < lenght / 2; i++) {
Object as = list.get(i);
list.set(i, list.get(lenght - 1 - i));
list.set(lenght - 1 - i, as);
}
}
public static void main(String[] args) {
LinkedList<Object> st = new LinkedList<Object>();
st.add(1);
st.add(2);
st.add(3);
st.add(4);
st.add(5);
Linkedtest.reverse(st);
System.out.println("Reverse Value will be:"+st);
}
}
This will be useful for any type of collection Object.
Related
Here is my program to fold a linked list using a Stack:
public Node middle(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public Node foldList(Node head){
Node mid = middle(head);
Node f = mid.next;
Stack<Node> stacks = new Stack<>();
if (head == null) return head;
while (f != null){
stacks.push(f);
f = f.next;
}
Node temp = head;
Node forv = head.next;
while(!stacks.isEmpty()) {
temp.next = stacks.pop();
temp = temp.next;
temp.next = forv;
temp = temp.next;
forv = forv.next;
}
return head;
}
Here is the code of the middle() and foldList() methods. When I run it it gets stuck in an infinite loop. Can anybody help me find out why this is happening?
The problem is that you are doing this:
linked list: 1-2-3-4-5-6
Put second half in a Stack:
linked list: 1-2-3-4-5-6
stack: 5-6
Insert the stack nodes between the linked list nodes:
linked list: 1-6-2-3-4-5-6-2-3-4-5-6-2-3-4-5-6.....infinite
You need to remove the second half of the nodes (the ones put on the stack) from the linked list before you start folding.
Since it's a linked list, you can simply nullify mid.next:
public Node foldList(Node head){
Node mid = middle(head);
Node f = mid.next;
// remove the second half
mid.next = null
Stack<Node> stacks = new Stack<>();
if (head == null) return head;
while (f != null){
stacks.push(f);
f = f.next;
}
Here's my full code, using Deque instead of Stack (because Stack is old and moldy):
import java.util.ArrayDeque;
import java.util.Deque;
public class LinkedListFolder {
public static void main(String[] args) {
Node head = createLinkedList();
foldList(head);
print(head);
}
private static Node createLinkedList() {
Node head = new Node(1);
Node current = head;
for (int i = 2; i < 7; i++) {
current.next = new Node(i);
current = current.next;
}
return head;
}
private static void print(Node node) {
System.out.println(node);
while (node.next != null) {
node = node.next;
System.out.println(node);
}
}
public static void foldList(Node head) {
if (head == null) {
return;
}
Deque<Node> nodesToFold = getNodesToFold(head);
Node current = head;
Node successor = head.next;
while (!nodesToFold.isEmpty()) {
current.next = nodesToFold.pop();
current = current.next;
current.next = successor;
current = current.next;
successor = successor.next;
}
}
private static Deque<Node> getNodesToFold(Node head) {
Node middle = findMiddle(head);
Node current = middle.next;
middle.next = null;
Deque<Node> nodesToFold = new ArrayDeque<>();
while (current != null) {
nodesToFold.push(current);
current = current.next;
}
return nodesToFold;
}
public static Node findMiddle(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
#Override
public String toString() {
return String.format("Node{value=%d}", value);
}
}
}
Output:
Node{value=1}
Node{value=6}
Node{value=2}
Node{value=5}
Node{value=3}
Node{value=4}
For the below code, I would like to know why the size of the linked list keeps giving me a null pointer exeption and why my pushEnd method to push a new node at the end doesnt work, it add an element after a few nodes and gets rid of rest.
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
/* Inserts a new Node at front of the list. */
public Node push(int data)
{
Node newNode = new Node(data);
newNode.next = head;
return head = newNode;
}
public Node pushEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
}
newNode.next = null;
while(head != null) {
head = head.next;
head.next = newNode;
return newNode;
}
return head;
}
public int getSize() {
int size = 0;
while(this.head != null) {
size++;
head = head.next;
}
return size;
}
public void printList() {
while (this.head !=null) {
System.out.print(head.data + "-->");
head = head.next;
}
System.out.println(head);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.push(35);
ll.push(100);
ll.push(14);
ll.push(44);
ll.push(10);
ll.push(8);
System.out.println("Created Linked list is:");
ll.printList();
System.out.println(ll.getSize());
}
}
I want to figure out the size of the linked list and be able to add nodes at the end.
Your while loops modify the head variable directly. This causes your other code to fail because now head is pointing to the last node in the list.
Create a new local variable for use in the while loops (instead of modifying head directly). That should fix it!
You are changing head reference, due to which you are getting incorrect output. You should make temp refer to head, do your operation using temp which will not affect head. It should be like below:
public class LinkedList {
Node head;
/* Inserts a new Node at front of the list. */
public void push(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void pushEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
newNode.next = null;
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
public int getSize() {
int size = 0;
Node temp = head;
while (temp != null) {
size++;
temp = temp.next;
}
return size;
}
public void printList() {
Node temp = this.head;
while (temp != null) {
System.out.print(temp.data + "-->");
temp = temp.next;
}
System.out.println(temp);
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
I am trying to write a simple class that reverse a singly linked list and return a constructed linked list. The code below is working if i make everything public which I dont want to. Anybody interested to address my question? (should I use doubly linked list? or it is possible with single link list?)
What I want is a function reverseList receives a ListNode Object return a ListNode Object (in reverse order). Like this:
originalNumber=OriginalNumber.reverseList();
//// my code
public class ReverseLinkList {
public static ListNode originalNumber=new ListNode();
public static ListNode reversedNumber=new ListNode();
public static void main(String[] args) {
//create 1->2->3->null
originalNumber.add(1);originalNumber.add(2);originalNumber.add(3);
System.out.print(num1.toString()+"\n");
//create 3->2->1->null
reversedNumber=originalNumber.reverseList;
}
}
class ListNode{
private class Node{
Object data;
Node next;
Node(int v){
data=v;
next=null;
}
public Object getData(){
return data;
}
public void setData(int v){
data=v;
}
public Node getNext(){
return next;
}
public void setNext(Node nextValue){
next=nextValue;
}
}
private Node head;
public void add(int data){
if(head==null){
head=new Node(data);
}
Node temp=new Node(data);
Node current=head;
if(current !=null){
while(current.getNext()!=null){
current=current.getNext();
}
current.setNext(temp);
}
}
public String toString(){
String output="";
if(head!=null){
Node current=head.getNext();
while(current!=null){
//System.out.println(output);
output+=current.getData().toString();
current=current.getNext();
}
}
return output;
}
public Node getHead(){
return head;
}
public static Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
}
The original and working code which I do not want
public class ReversedLinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
void printList(Node node) {
while (node != null) {
System.out.print(node.data + "");
node = node.next;
}
}
public static void main(String[] args) {
ReversedLinkedList list = new ReversedLinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.printList(head);
head = list.reverse(head);
System.out.println("");
list.printList(head);
}
}
You're on the right track. You can make the member variables private & use the appropriate getters & setters:
public ListNode reverseList() {
Node prev = null;
Node current = this.getHead();
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return this;
}
This allows you print a reversed list:
System.out.println(originalNumber.reverseList());
Note that the originalNumber is itself manipulated. So, subsequent prints (System.out.println(originalNumber);) would still print the reversed list.
If you don't want the original to be modified, then there really isn't any other way apart from collecting all the data & then looping through in the reverse order & adding them into a new list:
public ListNode reverseList() {
int size = 0;
// Calculate size
Node current = this.getHead();
while (current != null) {
size++;
current = current.getNext();
}
int[] data = new int[size];
// Collect all data
current = this.getHead();
int index = 0;
while (current != null) {
data[index++] = current.getData();
current = current.getNext();
}
// Add to a new list in reverse order
ListNode reversed = new ListNode();
for (index = size - 1; index >= 0; index--)
reversed.add(data[index]);
return reversed;
}
That first scan to get the size can be skipped if size is tracked while adding elements to the list or by simply switching to an ArrayList instead of an array for data.
Finally there's the elegant recursive approach which also keeps the original ListNode intact:
public ListNode reverseRecursive() {
return recursive(this.getHead());
}
private ListNode recursive(Node node) {
if (node == null)
return new ListNode();
else {
ListNode listNode = this.recursive(node.next);
listNode.add(node.data);
return listNode;
}
}
To print:
System.out.println(originalNumber.reverseRecursive());
Here we needn't keep track of size & you make use of the call stack to naturally keep track & pop out the nodes in reverse.
I have this linked list:
class Node {
Node next;
int num;
public Node(int val) {
num = val;
next = null;
}
}
public class LinkedList {
Node head;
public LinkedList(int val) {
head = new Node(val);
}
public void append(int val) {
Node tmpNode = head;
while (tmpNode.next != null) {
tmpNode = tmpNode.next;
}
tmpNode.next = new Node(val);
}
public void print() {
Node tmpNode = head;
while (tmpNode != null) {
System.out.print(tmpNode.num + " -> ");
tmpNode = tmpNode.next;
}
System.out.print("null");
}
public static void main(String[] args) {
LinkedList myList = new LinkedList(8);
myList.append(7);
myList.append(16);
myList.print();
}
}
and I want to know how should I sort this linked list? I tried to sort it but strange numbers starts comming out and in other cases it do nothing and sort nothing.
you can make the linked list sorted while insert itself. So that you dont need another function to sort it. You didn't consider the initial scenario where the head will be null only that is the error
public void insert(int val) {
Node currentNode = head;
Node nextNode = head.next;
if (head==null) {
head = new Node(val);
head.next = null;
return;
}
if (currentNode.num > val) {
Node tmpNode = head;
head = new Node(val);
head.next = tmpNode;
return;
}
if (nextNode != null && nextNode.num > val) {
currentNode.next = new Node(val);
currentNode.next.next = nextNode;
return;
}
while (nextNode != null && nextNode.num < val) {
currentNode = nextNode;
nextNode = nextNode.next;
}
currentNode.next = new Node(val);
currentNode.next.next = nextNode;
}
I have to implement a singly linked list for my project and I'm having trouble getting the remove method to work. I have searched on here for answers but I can't find any that incorporate the tail reference. My project needs to have a head and tail reference in the list and needs to be updated wherever necessary. This is my class and the remove method:
public class BasicLinkedList<T> implements Iterable<T> {
public int size;
protected class Node {
protected T data;
protected Node next;
protected Node(T data) {
this.data = data;
next = null;
}
}
protected Node head;
protected Node tail;
public BasicLinkedList() {
head = tail = null;
}
public BasicLinkedList<T> addToEnd(T data) {
Node n = new Node(data);
Node curr = head;
//Check to see if the list is empty
if (head == null) {
head = n;
tail = head;
} else {
while (curr.next != null) {
curr = curr.next;
}
curr.next = n;
tail = n;
}
size++;
return this;
}
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
if(head == null){
head = n;
tail = n;
}
n.next = head;
head = n;
size++;
return this;
}
public T getFirst() {
if (head == null) {
return null;
}
return head.data;
}
public T getLast() {
if(tail == null){
return null;
}
return tail.data;
}
public int getSize() {
return size;
}
public T retrieveFirstElement() {
// Check to see if the list is empty
if (head == null) {
return null;
}
Node firstElement = head;
Node curr = head.next;
head = curr;
size--;
return firstElement.data;
}
public T retrieveLastElement() {
Node curr = head;
Node prev = head;
// Check to see if the list is empty
if (head == null) {
return null;
} else {
// If there's only one element in the list
if (head.next == null) {
curr = head;
head = null;
} else {
while (curr.next != null) {
prev = curr;
curr = curr.next;
}
tail = prev;
tail.next = null;
}
}
size--;
return curr.data;
}
public void remove(T targetData, Comparator<T> comparator) {
Node prev = null, curr = head;
while (curr != null) {
if (comparator.compare(curr.data, targetData) == 0) {
//Check to see if we need to remove the very first element
if (curr == head) {
head = head.next;
curr = head;
}
//Check to see if we need to remove the last element, in which case update the tail
else if(curr == tail){
curr = null;
tail = prev;
prev.next = null;
}
//If anywhere else in the list
else {
prev.next = curr.next;
curr = curr.next;
}
size--;
} else {
prev = curr;
curr = curr.next;
}
}
}
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
#Override
public boolean hasNext() {
return current != null;
}
#Override
public T next() {
if(hasNext()){
T data = current.data;
current = current.next;
return data;
}
return null;
}
#Override
public void remove(){
throw new UnsupportedOperationException("Remove not implemented.");
}
};
}
}
I have went through many iterations of this method and each time I either lose the head reference, the tail reference or I don't remove the element and I am stumped trying to figure it out. For reference here is the test I'm running on it. I don't even fail the test, it just says failure trace.
public void testRemove(){
BasicLinkedList<String> basicList = new BasicLinkedList<String>();
basicList.addToEnd("Blue");
basicList.addToEnd("Red");
basicList.addToEnd("Magenta");
//Blue -> Red -> Magenta -> null
basicList.remove("Red", String.CASE_INSENSITIVE_ORDER);
//Blue -> Magenta -> null
assertTrue(basicList.getFirst().equals("Blue"));
//getLast() returns the tail node
assertTrue(basicList.getLast().equals("Magenta"));
}
EDIT: Forgot to mention that the remove method should be removing all instances of the target data from the list.
I see only 1 bug. If your list is initially empty the following method will cause a loop where you have one node whose next refers to itself:
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
// The list was empty so this if is true
if(head == null){
head = n;
tail = n;
}
n.next = head;
// now head == n and n.next == head == n so you've got a circle
head = n;
size++;
return this;
}
You can fix this like so:
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
if(head == null){
tail = n;
}
n.next = head;
head = n;
size++;
return this;
}