Undo Redo Program in Java using Data Structures
Welcome back again!
In this post we will learn that how actually we can undo and redo LinkedList in java programRequirements:
agenda:
Node
+data:String
+next:Node
LinkedList
+head: Node
+insertAtEnd(Node data):void
+undo():Node
+redo():void
LinkedList Runner
main()
Code for Node class public class Node { public String data; public Node next; public Node(String data) { this.data = data; this.next = null; } }
Code for LinkedList class
public class LinkedList{ public Node head; public String str = ""; public LinkedList() { head = null; } public void insertAtEnd(Node node) { if(isEmpty()) head = node; else { Node curr = head; while(curr.next!=null) { curr = curr.next; } curr.next = node; } } public void redo() { if(str.equals("")) return; else { insertAtEnd(new Node(str.charAt(str.length()-1)+"")); str = str.replaceAll(str.charAt(str.length()-1)+"", ""); } } public Node undo() { if(isEmpty()) return null; else { Node curr = head; while(curr.next.next != null) { curr = curr.next; } Node temp = curr.next; str+=temp.data; curr.next = null; return temp; } } public boolean isEmpty() { return head == null; } public void showAll() { if(isEmpty()) System.out.println("LinkedList is empty"); else { Node curr = head; while(curr!=null) { System.out.println(curr.data); curr = curr.next; } } }end methods }end class
Code for Runner class
public class LinkedListRunner {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertAtEnd(new Node("A"));
list.insertAtEnd(new Node("B"));
list.insertAtEnd(new Node("C"));
list.insertAtEnd(new Node("D"));
list.insertAtEnd(new Node("E"));
list.showAll();
System.out.println("_____undo_________");
Node result = list.undo();
Node result2 = list.undo();
Node result3 = list.undo();
// System.out.println(result.data);
// System.out.println(result2.data);
// System.out.println(result3.data);
list.showAll();
System.out.println("____________after redo__________");
list.redo();
list.redo();
// System.out.println(list.str);
list.showAll();
}
}
|
Comments
Post a Comment
Let me know your doubts