package com.etime;
public class ReverseLinkedList {
public static void main(String[] args) {
Node head = new Node();
head.setData(1);
Node node2 = new Node();
node2.setData(2);
head.setNext(node2);
Node node3 = new Node();
node3.setData(3);
node2.setNext(node3);
System.out.println(head);
Node revers = revers(head);
System.out.println(revers);
}
public static Node revers(Node head){
Node currentNode = head;
Node currentNext = null;
if(currentNode.hasNext()){
currentNext = head.getNext();
}else {
return currentNode;
}
while (currentNode.hasNext()){
Node temp = null;
if(currentNext.hasNext()){
temp = currentNext.getNext();
}else {
break;
}
head.setNext(null);
currentNext.setNext(currentNode);
currentNode = currentNext;
currentNext = temp;
}
currentNext.setNext(currentNode);
return currentNext;
}
static class Node{
private Integer data;
private Node next;
public Node() {
}
public Node(Integer data, Node next) {
this.data = data;
this.next = next;
}
public void setData(Integer data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
public Integer getData(){
return this.data;
}
public Node getNext() {
return next;
}
public boolean hasNext(){
return next != null;
}
@Override
public String toString() {
if(this.hasNext()){
return this.data.toString() + "," +this.next.toString();
}else {
return this.data.toString();
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101