上次刷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;
}
程序运行结果: