Coding Interviews 3 Linked List

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.

posted @ 2015-09-17 04:02  Bogart2015  阅读(169)  评论(0编辑  收藏  举报