码迷,mamicode.com
首页 > 其他好文 > 详细

从尾到头打印链表

时间:2015-04-08 12:38:50      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

题目: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 }

 

从尾到头打印链表

标签:

原文地址:http://www.cnblogs.com/ykzou/p/4401707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!