class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.last_node = None def prepend(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def push(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next def insert_after(self, prev_node, data): if not prev_node: print('Given node not present in the list') return new_node = Node(data) new_node.next = prev_node.next prev_node.next = new_node def pswap(self): temp = self.head if temp is None: return while (temp is not None and temp.next is not None): temp.data, temp.next.data = temp.next.data, temp.data temp = temp.next.next def display(self): current = self.head while current: print(current.data, end=' ') current = current.next llist = LinkedList() T = int(input()) for x in range(T): d = int(input()) llist.push(d) llist.display() llist.pswap() print() llist.display()
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter