标签:
Linked list is a one of the most important topic in interviews. Because it uses dynamic memory and short lines can finish its implement. It is often used as test question.
Here is the structure of a node of linked list
typedef struct Node { int val; struct Node* pnext; }Node;
Add new node function:
void AddNew(Node** phead, int value) { Node* pnew = new Node; pnew->pnext = NULL; pnew->val = value; if (NULL == *phead){ *phead = pnew; return; } else{ Node* pnode = *phead; while (pnode->pnext != NULL){ pnode = pnode->pnext; } pnode->pnext = pnew; } }
Why would I use the pointer to pointer instead of a pointer to head node. Because if the pointer to head is NULL, then we should set the node as head. However, if we use pointer we cannot change the pointer, since it is just a copy, then the head still is NULL.
Delete a existing node:
void NodeExecution::RemoveNode(Node** phead, int value) { //Node** phead = &head; //this is for class if (phead == NULL || *phead == NULL) return; Node* toDeleteNode = NULL; if ((*phead)->val == value){ toDeleteNode = *phead; *phead = (*phead)->pnext; } else{ Node* pnode = *phead; while (pnode->pnext != NULL&&pnode->pnext->val != value){ pnode = pnode->pnext; } if (pnode->pnext != NULL && pnode->pnext->val == value){ toDeleteNode = pnode->pnext; pnode->pnext = pnode->pnext->pnext; } } if (NULL != toDeleteNode){ delete toDeleteNode; toDeleteNode = NULL; } }
Output the value of linked list in reverse direction:
void PrintReverse(Node* phead) { std::stack<int> stackNode; Node* p = phead; while (p != NULL){ stackNode.push(p->val); p = p->pnext; } while (!stackNode.empty()){ printf("%d\t", stackNode.top()); stackNode.pop(); } }
Since recursion basically is a stack structure, so we can also code like below:
void NodeExecution::PrintReverseRecursion(Node *phead) { if (NULL != phead) { if (NULL != phead->pnext) { PrintReverseRecursion(phead->pnext); } printf("%d\t", phead->val); } }
Although in this way, it is clear. if list is too long, maybe this method would lead to stack leak. Robust is better for the first way.
Coding Interviews 3 Linked List
标签:
原文地址:http://www.cnblogs.com/Bogart/p/4815100.html