Created
April 18, 2011 23:31
-
-
Save paxswill/926513 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
using namespace std; | |
// So here I'll define a struct that will go in the linked list | |
typedef struct person{ | |
string name; | |
int age; | |
}; | |
// Now let's make a linked list node | |
typedef struct node{ | |
person p; | |
node *next; | |
}; | |
int main (int argc, char const *argv[]) | |
{ | |
// This is the only persistent reference to the linked list you have, head | |
node *head; | |
return 0; | |
} | |
/* | |
For the following examnples, refer to this list | |
a -> b -> c -> d -> e -> f | |
head points to a | |
*/ | |
/* | |
To delete a node, say in this example, c, we need to have references to the node before it, | |
and the node in front of it. | |
node *previous = b; | |
node *next = d; | |
Delete c | |
delete c; | |
Now have b point to d | |
b->next = d; | |
All done. | |
Special case: If you are deleting the node at the end, you just have to set the new end's next variable to NULL. Ex: | |
delete f; | |
e->next = NULL; | |
*/ | |
/* | |
Let's say we want to insert a node between c and d. | |
First, get a reference to the previous and next nodes | |
node *previous = c; | |
node *next = d; | |
Now create your new node | |
node *newNode = new node; | |
Now insert it into the chain | |
c->next = newNode; | |
newNode->next = d; | |
That's it. | |
Special Case: To add to the end of the list, just have the end point to the new node. Ex: | |
f->next = newNode; | |
newNode->next=NULL; | |
*/ | |
// To move nodes, you can use a combination of the delete and insert steps |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment