Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to convert linked list by alternating nodes from front and back in Python
Suppose we have a singly linked list, we have to rearrange it such that we take: the last node, and then the first node, and then the second last node, and then the second node, and so on.
So, if the input is like [1,2,3,4,5,6,7,8,9], then the output will be [9, 1, 8, 2, 7, 3, 6, 4, 5, ]
To solve this, we will follow these steps:
c := node
l := a new list
-
while c is not-null, do
insert value of c at the end of l
c := next of c
c := node
-
while c is not null and l is non-empty, do
value of c := value of last element from l and delete it
c := next of c
-
if c is null, then
come out from the loop
value of c := value of last element from l and delete it
c := next of c
return node
Let us see the following implementation to get better understanding:
Example
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, node):
c = node
l = []
while c:
l.append(c.val)
c = c.next
c = node
while c and l:
c.val = l.pop()
c = c.next
if c == None:
break
c.val = l.pop(0)
c = c.next
return node
ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9])
print_list(ob.solve(head))
Input
[1,2,3,4,5,6,7,8,9]
Output
[9, 1, 8, 2, 7, 3, 6, 4, 5, ]
Advertisements