码迷,mamicode.com
首页 > 其他好文 > 详细

Coding Interviews 3 Linked List

时间:2015-09-17 06:29:07      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!