C++练习 | 创建并正序输出不带头结点的链表
#include <iostream> #include <cstdio> #include <stdlib.h> using namespace std; struct list { int data; list *next; }list1; list *initlist(int num) {//定义一个新节点 list *node=(list*)malloc(sizeof(list)); node->data=num; node->next=NULL; return node; } void pushback(list **pplist,int num) { if(*pplist==NULL) *pplist=initlist(num); else if((*pplist)->next==NULL) (*pplist)->next=initlist(num); else { list *tail=*pplist; while(tail->next) { tail=tail->next;//通过依次指向找到next为空的尾结点 } tail->next=initlist(num);//在最后添加一个结点 } } void print(list *x) { if(x==NULL) { cout<<"->NULL"<<endl; return; } cout<<"->"<<x->data; x=x->next; print(x); } int main(int argc, const char * argv[]) { freopen("1.in","r",stdin); list *l=NULL; int t; while(cin>>t) { pushback(&l, t); } print(l); return 0; }