views:

1310

answers:

5

I want to implement UNDO and REDO option(as we see in MS word etc). Can you suggest me a data structure for it, and how can i implement it.?

+36  A: 

It isn't a data structure but a design pattern. You're looking for the Command Pattern.

The standard is to keep the Command objects in a stack to support multi level undo. In order to support redo, a second stack keeps all the commands you've Undone. So when you pop the undo stack to undo a command, you push the same command you popped into the redo stack. You do the same thing in reverse when you redo a command. You pop the redo stack and push the popped command back into the undo stack.

Jason Punyon
right on jason. +1 on you ;-)
Raj
Also it's important to always clear the Redo stack if you push another command.
Balk
Data structure is Stack with instances of "Command" objects.
zdmytriv
+2  A: 

Objective-C Cocoa has a well documented anwser named NSUndoManager.

mouviciel
+1  A: 

You can use Command Pattern to achive Undo/Redo

Check these samples:

http://www.codeproject.com/csharp/undoredobuffer.asp

http://www.dofactory.com/Patterns/PatternCommand.aspx

NinethSense
+5  A: 

Actually, the standard pattern for this functionality (Gang of Four, even) is Memento.

Also, while most programs use Undo/Redo stacks, afficionados of certain text editors prefer Undo/Redo trees so that they don't lose their entire history if they undo a few commands, try a new one, and change their minds.

Hank Gay
You're right. If you add more info about how it interacts with the command pattern, this would be a great answer.
Kieveli