链表的建立并返回链表头

上次刷leetcode这里,关于返回链表头我犯了一个错,当链表第一个元素赋值的时候,需要这个指针copy下来,就是链表头的地址

#include<bits/stdc++.h>
using namespace std;
typedef struct st{
int x;
struct st*next;
}Node;
int main()
{
    int n;
    cout<<"how many numbers you want to input:";
    cin>>n;
    Node *head=NULL,*tail,*tmp=NULL;
    tail=head;
    int t;
    for(int i=0;i<n;i++)
    {
        cin>>t;
        tmp=(Node*)malloc(sizeof(Node));
        tmp->x=t;
        tmp->next=NULL;
        if(tail==NULL)
        {
            tail=tmp;
            tail->next=NULL;
            head=tail;//把链表头地址复制下来
        }
        else
        {
            tail->next=tmp;
            tail=tmp;
        }

    }
    while(head!=NULL)
    {
        cout<<head->x<<endl;
        head=head->next;
    }
    return 0;
}

程序运行结果:

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/85100687
今日推荐