zoukankan      html  css  js  c++  java
  • 无结点单链表反转

    两种方法:新建链表头插法就地反转法

     1 #include<iostream>
     2 using namespace std;
     3 
     4 
     5 struct ListNode {
     6     int val;
     7     ListNode *next;
     8     ListNode(int x) : val(x), next(NULL) {}
     9 };
    10 
    11 //新建链表头插法
    12 ListNode* reverseList(ListNode* head) {
    13     if (head == NULL)
    14         return head;
    15     ListNode* p=NULL;
    16     ListNode* pCur = head;
    17     while (pCur != NULL)
    18     {
    19         ListNode* newNode = new ListNode(pCur->val);
    20         newNode->next = p;
    21         p = newNode;
    22         pCur = pCur->next;
    23     }
    24     return p;
    25 }
    26 
    27 //就地反转法
    28 ListNode* reverseList1(ListNode* head)
    29 {
    30     if (head == NULL || head->next == NULL)
    31         return head;
    32     ListNode* pre = head;
    33     ListNode* pCur = head->next;
    34     while (pCur!=NULL)
    35     {
    36         pre->next = pCur->next;
    37         pCur->next = head;
    38         head = pCur;
    39         pCur = pre->next;
    40     }
    41     return head;
    42 }
    43 
    44 int main()
    45 {
    46     ListNode* head=new ListNode(0);
    47     ListNode* node1 = new ListNode(1);
    48     ListNode* node2 = new ListNode(2);
    49     ListNode* node3 = new ListNode(3);
    50     ListNode* node4 = new ListNode(4);
    51     ListNode* node5 = new ListNode(5);
    52     head->next = node1;
    53     node1->next = node2;
    54     node2->next = node3;
    55     node3->next = node4;
    56     node4->next = node5;
    57     node5->next = NULL;
    58 
    59     ListNode* pCurrent = head;
    60     while (pCurrent != NULL)
    61     {
    62         cout << pCurrent->val << " ";
    63         pCurrent = pCurrent->next;
    64     }
    65     cout << endl << endl;
    66 
    67     ListNode* node= reverseList1(head);
    68 
    69     ListNode* pCurrent1 = node;
    70     while (pCurrent1 != NULL)
    71     {
    72         cout << pCurrent1->val << " ";
    73         pCurrent1 = pCurrent1->next;
    74     }
    75     cout << endl << endl;
    76 
    77     return 0;
    78 }
  • 相关阅读:
    $_SERVER
    下面介绍mysql中模糊查询的四种用法:
    qq第三方登录
    远程连接数据库出错
    lnmp中的tp的pathinfo模式
    TP5配置所谓的url_moudel
    tp3.2.3中的xss攻击基本防护
    tp中的Csv文件读取(原创)
    mysql语句整理
    SVN的详细使用
  • 原文地址:https://www.cnblogs.com/hl249853856/p/10481615.html
Copyright © 2011-2022 走看看