In Python, I have to implement Double linked list where each node stores one lin
ID: 3719396 • Letter: I
Question
In Python, I have to implement Double linked list where each node stores one line as a separate class to test the following functions for each class: (1) cmd_h: move cursor one character to the left (2) cmd_I: move cursor one character to the right (3) cmd_j: move cursor vertically one line (4) cmd_k: move cursor vertically one line (5) cmd_X: delete the character to the left of the cursor (6) cmd_D: remove on current line from cursor to the end (7) cmd_dd: delete current line and move cursor to the beginning of next line (8) cmd_ddp: transpose two adjacent lines (9) cmd_n: search for next occurrence of a string (assume that string to be searched is fully in one line. (10) cmd_wq: write your representation as text file and save it
Explanation / Answer
Double Linked List in Python
class Node(object):
def __init__(self, data, previous, nxt):
self.data = data
self.previous = previous
self.nxt = nxt
class DoubleLinkedList(object):
head = None
tail = None
def insert(self, data):
new_node = Node(data, None, None)
if self.head is None:
self.head = self.tail = new_node
else:
new_node.previous = self.tail
new_node.nxt = None
self.tail.nxt = new_node
self.tail = new_node
def delete(self, node_value):
current_node = self.head
while current_node is not None:
if current_node.data == node_value:
if current_node.previous is not None:
current_node.previous.nxt = current_node.nxt
current_node.nxt.previous = current_node.previous
else:
self.head = current_node.nxt
current_node.nxt.previous = None
current_node = current_node.nxt
def display(self):
print "Display list data:"
current_node = self.head
while current_node is not None:
print current_node.previous.data if hasattr(current_node.previous, "data") else None,
print current_node.data,
print current_node.nxt.data if hasattr(current_node.nxt, "data") else None
current_node = current_node.nxt
print "*"*50
d = DoubleLinkedList()
d.insert(5)
d.insert(6)
d.insert(50)
d.insert(30)
d.display()
d.delete(50)
d.delete(5)
d.display()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.