Home > Programming > Java: How to reverse a linked list

Java: How to reverse a linked list


public class ListNode<T>
{
T data;
ListNode<T> next;
public ListNode(T data)
{
this.data = data;
}
}
public class ListNode<T>{ T data; ListNode<T> next; public ListNode(T data) { this.data = data; }}

public class LinkedList<T>

{

ListNode<T> head;

public void add(T data)

{

ListNode<T> node = new ListNode<T>(data);

if ( head == null )

{

head = node;

}

else

{

node.next = head;

head = node;

}

}

public void reverse()

{

ListNode<T> curr = head;

ListNode<T> nxt = null;

ListNode<T> last = null;

while ( curr != null )

{

nxt = curr.next;

curr.next = last;

last = curr;

curr = nxt;

}

head = last;

}

public String toString()

{

StringBuilder strbld = new StringBuilder();

ListNode<T> curr = head;

while( curr != null )

{

strbld.append(curr.data.toString() + " ");

curr = curr.next;

}

return strbld.toString();

}

}

Advertisements
  1. January 3, 2015 at 8:19 pm

    You post interesting content here. Your website deserves much
    bigger audience. It can go viral if you give it initial boost, i know very useful tool that can help you, just search in google:
    svetsern traffic tips

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: