/* clist.cpp * Anthony Larrain * * An example of using a simple node struct to create a C-Style linked list. * The chaining of nodes is being done in main. */ #include #include using namespace std; struct node { int data; node *next; }; void printList(const node *cursor, ostream &out); int size(const node *cursor); void copyList(const node *cursor, node *©Head, node *©Tail); int main() { //Creating two pointers node *head, *tail; head = tail = NULL; /* Allocating memory for a node object(nameless) returning address to head -------- | | | head -> | | | -------- */ head = new node; head -> data = 20; head -> next = NULL; tail = head; /* ---------- head-> | | |________ tail-> | 20 | | | ----------- | --- ------ NULL */ printList(head, cout); /* allocating a new node object, returning the address and assigning it to tail's next field. */ tail -> next = new node; // pointing tail to the newly created node object. tail = tail -> next; tail -> data = 30; tail -> next = NULL; printList(head, cout); // adding another integer to the back of the list tail -> next = new node; tail = tail -> next; tail -> data= 10; tail -> next = NULL; printList(head, cout); for(int i = 0; i < 5; i++) { tail -> next = new node; tail = tail -> next; tail -> data = i * 3; tail -> next = NULL; } printList(head, cout); cout << "the size of the list is " << size(head) << endl; // insert a new node at the front node *newHeadNode = new node; newHeadNode -> data = 44; newHeadNode -> next = head; head = newHeadNode; printList(head, cout); // insert a new node at the back; node* newTailNode = new node; newTailNode->data=11111; newTailNode->next = NULL; tail->next = newTailNode; tail = newTailNode; printList(head, cout); node *copyHead, *copyTail; copyList(head,copyHead,copyTail); printList(copyHead, cout); // change the copy copyHead -> data = 99999; printList(head, cout); printList(copyHead, cout); system("pause"); return 0; } void printList(const node *cursor, ostream &out) { while(cursor != NULL){ out << cursor -> data <<" "; cursor = cursor -> next; } out << endl; return; } int size(const node *cursor) { int count(0); //const node *cursor = hd; while(cursor != NULL){ ++count; cursor = cursor -> next; } return count; } void copyList(const node *cursor, node *©Head, node *©Tail) { if(cursor == NULL) { return; } // copy first node copyHead = copyTail = new node; copyHead -> data = cursor -> data; copyHead -> next = NULL; cursor = cursor -> next; // add the rest to the end for(; cursor != NULL; cursor = cursor -> next){ copyTail -> next = new node; copyTail = copyTail -> next; copyTail -> data = cursor -> data; copyTail -> next = NULL; } }