zoukankan      html  css  js  c++  java
  • [面试] 在单链表末尾添加一个节点 C++ 实现

    /*
     *  C++ 用指针的引用,好多了! 考虑得更简单。 
     */ 
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #define BUG cout << "here\n";
    #define STOP system("pause");
    
    using namespace std;
    
    struct node {
        int value;
        node* next;
        node() {
            value = 0;
            next = NULL;
        }
    };
    void addToTail(node* &phead, int value) {
        node* pn = new node();
        pn->value = value;
        if(phead == NULL) { // 考虑要全面。 
            phead = pn;
        }
        else {
            node* p = phead;
            while(p->next != NULL) {
                p = p->next;
            }
            p->next = pn;
        }
    }
    
    void addToTail(node** phead, int value) { // 之所以用指向指针的指针 -- 理解  复杂化的简单对比思想来理解 
        node* pn = (node*)malloc(sizeof(node));
        pn->next = NULL;
        pn->value = value;
        if(*phead == NULL) { // 考虑要全面。 
            *phead = pn;
        }
        else {
            node* p = *phead;
            while(p->next != NULL) {
                p = p->next;
            }
            p->next = pn;
        }
    }    
    int main() {
        node* head = NULL;
        addToTail(&head, 10);
        addToTail(&head, 20);
        node* p = head;
        while(p != NULL) {
            printf("%d->", p->value);
            p = p->next;
        }
        printf("NULL");
        STOP
        return 0;
    }
      
    
    
    
    
    
    
    
    
  • 相关阅读:
    保险
    cron表达式的用法
    Hive 学习记录
    股票的五种估值方法
    AtCoder Beginner Contest 113 A
    ZOJ 4070 Function and Function
    银行业务队列简单模拟 (数据结构题目)
    算法3-7:银行排队
    算法3-5:n阶Hanoi塔问题
    算法3-1:八进制数
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787148.html
Copyright © 2011-2022 走看看