• 无结点单链表反转


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

     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 }
  • 相关阅读:
    [Writeup]奇怪的单点音
    [Writeup]百度一下,你就知道
    C语言学习一个月后感想
    小黄衫获得感想及经验总结
    Ubuntu初始化配置
    在Ubuntu 18.04中安装 docker compose
    Docker安装 配置
    Laravel Heroku评价
    Laravel Deploy to Heroku
    Laravel Nuxt auth refresh
  • 原文地址:https://www.cnblogs.com/hl249853856/p/10481615.html
Copyright © 2020-2023  润新知