链表的建立与遍历

 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct ListNode {
 5     int m_nKey;
 6     ListNode* m_pNext;
 7 };
 8 
 9 void createList(ListNode *pHead) {
10     ListNode *p = pHead;
11     ListNode *n;
12 
13     while(true) {
14         int key;
15         scanf("%d",&key);
16         if(0 == key)
17             break;
18         n = (ListNode*)malloc(sizeof(ListNode));
19         n->m_nKey = key;
20         p->m_pNext = n;
21         p = n;
22     }
23     p->m_pNext = NULL;
24 }
25 void PrintList(ListNode *pHead) {
26     if(pHead == NULL && pHead->m_pNext == NULL)
27         return;
28     ListNode *p = pHead->m_pNext;
29     while(NULL != p) {
30         printf("%d ", p->m_nKey);
31         p = p->m_pNext;
32     }
33 
34 }
35 
36 int main()
37 {
38     ListNode *pHead;
39     pHead = (ListNode*)malloc(sizeof(ListNode));
40     createList(pHead);
41     PrintList(pHead);
42     return 0;
43 }

 

posted @ 2014-06-06 10:50  soul390  阅读(152)  评论(0)    收藏  举报