面试题5:从尾到头打印链表

题目链接:http://ac.jobdu.com/problem.php?pid=1511

思路:修改链表的指向。

使用三个指针head pRes pNext

保存pRes = head
保存head = pNext->next
修改pNext->next = pRes
更新pRes = pNext
更新pNext = head

code:

 1 #include <cstdio>
 2 using namespace std;
 3 struct node
 4 {
 5     int nValue;
 6     struct node* next;
 7 };
 8 node* reserveNodeList(node* head)
 9 {
10     if (head == NULL) return NULL;
11     node* pRes = head;
12     node* pNext = head->next;
13     head->next = NULL;
14     while (pNext != NULL)
15     {
16         head = pNext->next;
17         pNext->next = pRes;
18         pRes = pNext;
19         pNext = head;
20     }
21     head = pRes;
22     return head;
23 }
24 int main()
25 {
26     int n;
27     scanf("%d", &n);
28     if (n == -1) return 0;
29     node* head = new node;
30     head->nValue = n;
31     head->next = NULL;
32     node* p = head;
33     while (scanf("%d", &n), n != -1)
34     {
35         node* pCurrent = new node;
36         p->next = pCurrent;
37         pCurrent->nValue = n;
38         pCurrent->next = NULL;
39         p = p->next;
40     }
41     head = reserveNodeList(head);
42     while (head != NULL)
43     {
44         printf("%d\n", head->nValue);
45         head = head->next;
46     }
47     return 0;
48 }

 

posted @ 2015-04-08 10:27  jasaiq  阅读(135)  评论(0编辑  收藏  举报