# Program to reverse a linked list

Abhishek Kumar Category: Data StructuresTags: datastructures reverse linkedlist

Given a linked list, write a program to reverse elements of a linked list. e.g.- for linked list 1 -> 2 -> 3 -> 4 -> 5, output should be 5 -> 4 -> 3 -> 2 -> 1.

#### Problem-

Reverse elements of a linked list.

#### Solutions-

Solution 1: (Iterative solution) - some solution.

#### Program (Iterative)

``````class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

def insertAtEnd(self, data):
node = Node(data)
if self.head is None:
else:
while temp.next:
temp = temp.next
temp.next = node

def traverse(self):
while temp:
print(temp.data, end=' ')
temp = temp.next
print()

def reverse(self):
prev = None
nextTemp = temp.next
while nextTemp:
temp.next = prev
prev = temp
temp = nextTemp
nextTemp = nextTemp.next
temp.next = prev

print('Before reversing:')
print('After reversing:')
``````class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}

}

public void insertAtEnd(int data) {
if (head == null) {
head = new Node(data);
}
else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Node(data);
}
}

public void traverse() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}

public void reverse() {
Node temp = head;
Node prev = null;
Node nextTemp = temp.next;
while(nextTemp != null) {
temp.next = prev;
prev = temp;
temp = nextTemp;
nextTemp = nextTemp.next;
}
temp.next = prev;
}
}

class Main {
public static void main(String[] args) {
ll.insertAtEnd(5);
ll.insertAtEnd(1);
ll.insertAtEnd(6);
ll.insertAtEnd(8);
ll.insertAtEnd(9);
System.out.println("Before reversing: ");
ll.traverse();
System.out.println("After reversing: ");
ll.reverse();
ll.traverse();
}
}``````

#### Output

Output

```Before reversing:
5 1 6 8 9
After reversing:
9 8 6 1 5```

AUTHOR

### Abhishek Kumar

Software engineer | Blogger | Keen learner
Python | Django | JavaScript | React | Next.js | Express.js | C
Passionate about learning and experimenting with new things and open to more opportunities and collaborations.