zoukankan      html  css  js  c++  java
  • 面试题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
    ", head->nValue);
    45         head = head->next;
    46     }
    47     return 0;
    48 }
  • 相关阅读:
    maven资源文件的相关配置
    servlet-url-pattern匹配规则详细描述
    Spring的单例模式底层实现
    jsf--小项目--爱群小店
    jsf--页面循环跳转,项目内容递交
    查看MySQL路径
    HTML和XHTML的区别是什么
    Jsf 页面导航Navigation总结
    h:commandButton
    JSF--INTRODUCION
  • 原文地址:https://www.cnblogs.com/ykzou/p/4401707.html
Copyright © 2011-2022 走看看