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
Categories: Programming
Tags: java, java list, linked list, list, reverse, reverse linked list, reverse list, reverse list in java, reversing a list
Leave a Reply Cancel reply
Recent Posts
- Java Parsing RSS XML using XPath
- C# Get Physical Device ID from Drive Letter or Logical Disk ID
- A 4.0 GPA only does not necessarily guarantee a job
- How come Computer Science Graduates are valued less than Contractors?
- Scala vs Python: Read File
- Qualities of a Great Teacher
- Letter Frequency Counter Using LINQ
- C# Tuples vs Anonymous Types
- C# Read a file from web (http)
- Better solution first or just the solution first?
Blog History
- 58,221 views
Calendar of Events
Clusters
Advertisements
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