Skip to content

Commit 0de78cb

Browse files
anish03abranhe
authored andcommitted
Python implementation for recursively reversing a linkedlist
1 parent 2d209d6 commit 0de78cb

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

linkedlist/reverse_linkedlist.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Recursively reverse a linked list
2+
3+
class Node:
4+
def __init__(self,data):
5+
self.data = data
6+
self.next = None
7+
8+
class LinkedList:
9+
def __init__(self):
10+
self.head = None
11+
self.tail = None
12+
self.count = 0
13+
14+
def isEmpty(self):
15+
if self.count == 0:
16+
return True
17+
return False
18+
19+
def addnode(self,data):
20+
new = Node(data)
21+
if self.isEmpty():
22+
self.head = new
23+
self.tail = new
24+
self.count += 1
25+
else:
26+
new.next = self.head
27+
self.head = new
28+
self.count += 1
29+
30+
def show(self):
31+
list = ''
32+
ptr = self.head
33+
while ptr:
34+
list += str(ptr.data)
35+
list += '->'
36+
ptr = ptr.next
37+
print list
38+
39+
def reverse(self,cur):
40+
cur = cur
41+
n = cur.next
42+
43+
if n.next:
44+
self.reverse(cur.next)
45+
n.next = cur
46+
cur.next = None
47+
else:
48+
n.next = cur
49+
self.head = n
50+
51+
def main():
52+
L = LinkedList()
53+
L.addnode(89)
54+
L.addnode(67)
55+
L.addnode(21)
56+
L.addnode(32)
57+
L.addnode(2)
58+
L.show()
59+
L.reverse(L.head)
60+
L.show()
61+
62+
63+
if __name__ == '__main__':
64+
main()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy