链表
建立单向链表
尾插法:(建法虽然简单,但是会多一个没用的头指针)
struct ListNode{
int m_key;
ListNode* next;
};
ListNode* CreatList(int n){
ListNode* head=(ListNode*)malloc(sizeof(ListNode)); //申请空间
ListNode* q=nullptr;
ListNode* r=head;
for(int i=0;i<n;i++){
q=(ListNode*)malloc(sizeof(ListNode));
cin>>q.m_key; //键盘输入,这步十分重要
r->next=q; //新建的节点插入尾部
r=q; //跟新尾节点
}
r->next=nullptr; //这一步没有的话会死掉,因为两个地方都指向q了
return head; //返回头节点
}
int main()
{
int n;
while(cin>>n){
ListNode* head=CreatList(n);//这里要注意,其实数据head->next才有效
}
}