《从尾到头输出链表》关于头指针的问题

关于链表的头指针问题

在数据结构中十分常见,今天在做一道题《从尾到头输出链表》的时候,发现一个问题:

那就是不同算法中对链表的头指针理解不一样。所以写此文章来记录自己碰到的问题:

1、在牛客网中,练习链表的“从尾到头输出链表”,发现它所默认的头指针head是直接指向链表中第一个数据的。所以,如果链表中的第一个数据有值的话。那么直接head->value就可以输出该值。

2、在自己练习的链表创建和输出中(见下面的代码,链表的创建和输出),由于创建时,我定义的head头指针是不存任何数据的一个空指针,但是它的next是指向链表中的第一个数据的。所以,在从尾到头输出链表时,我应该做如下判断

while (head->next != NULL){
        stk.push(head->next->value);
        head = head->next;
}

链表的创建、输出、从尾到头输出的源代码如下:

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

struct ListNode
{
    int value;
    ListNode* next;
};

ListNode* creatLinkTable(int);
void PrintLinkTable(ListNode*);
vector<int> printListFromTailToHead(ListNode*);

int main(){
    int n;
    ListNode* head;
    cout << "创建链表的长度n为:";
    cin >> n;
    head = creatLinkTable(n);
    PrintLinkTable(head);
    vector<int> val=printListFromTailToHead(head);
    for (int i = 0; i < val.size(); i++){
        cout << val[i] << " ";
    }
    system("pause");
}

//根据指定长度,创建链表
ListNode* creatLinkTable(int n){
    //头结点的指针
    ListNode* head;
    ListNode *pNode, *pHead;
    int input;
    head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    pHead = head;
    for (int i = 0; i < n; i++){
        pNode = (ListNode*)malloc(sizeof(ListNode));
        cin >> input;
        pNode->value = input;
        pNode->next = NULL;
        pHead->next = pNode;
        pHead = pHead->next;
    }
    return head;
}

//正常顺序输出链表
void PrintLinkTable(ListNode* head){
    ListNode *pNode;
    pNode = head;
    if (pNode->next == NULL){
        cout << "链表中没有值" << endl;
    }
    else{
        while (pNode->next != NULL){
            cout << pNode->next->value << " ";
            pNode = pNode->next;
        }
    }
}

//从尾到头输出链表
vector<int> printListFromTailToHead(ListNode* head){
    stack<int> stk;
    vector<int> value;
    while (head->next != NULL){
        stk.push(head->next->value);
        head = head->next;
    }
    while (!stk.empty()){
        value.push_back(stk.top());
        stk.pop();
    }
    return value;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值