在操作单链表之前需要对其进行初始化之类的工作,下面通过具体的代码来说明其初始化方法:
1 #include2 using namespace std; 3 typedef struct Listnode 4 { 5 int data; 6 struct Listnode *next; 7 Listnode(int x):data(x),next(NULL){} 8 9 }Listnode;10 Listnode *createList()11 {12 Listnode *prehead = new Listnode(-1);13 return prehead;14 }15 Listnode *initList(Listnode *preheadInit)16 {17 int a[] = { 1,2,3,4,5,6,7,8,9};18 Listnode *cur,*head;19 cur = preheadInit;20 for(int i = 0;i < sizeof(a)/sizeof(a[0]);i++)21 {22 Listnode *p = new Listnode(a[i]);23 cur->next = p;24 cur = cur->next;25 }26 head = preheadInit;27 return head->next;28 }29 void showList(Listnode *head)30 {31 while(head)32 {33 cout << head->data << endl;34 head = head->next;35 }36 }37 38 39 40 int main()41 {42 Listnode *prehead = createList();43 Listnode *head = initList(prehead);44 showList(head);45 }
输出的结果就是1 2 3 4 5 6 7 8 9。