zoukankan      html  css  js  c++  java
  • Reverse Linked List

    Reverse a singly linked list.

    思路:

    to slove this problem, I choose a recurrent method, to reverse linked-list nodes one-by-one.

    first, point head to NULL.(make the head be a tail)

    and then, point cur node to prev node, and then, move prev pointer to cur node, move cur pointer to next node.

    until next node move to NULL.

    *recursive(递归),recurrent(递推)

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* reverseList(ListNode* head) {
    12         if (head == NULL || head->next == NULL) {
    13             return head;
    14         }
    15         ListNode *prev = head, *cur = head->next, *next = cur->next;
    16         head->next = NULL;
    17         while (next != NULL) {
    18             cur->next = prev;
    19             prev = cur;
    20             cur = next;
    21             next = next->next;
    22         }
    23         cur->next = prev;
    24         return cur;
    25     }
    26 };
  • 相关阅读:
    Linux rcp命令详解
    Linux patch命令详解
    Linux paste命令详解
    linux od命令详解
    linux mv命令详解
    Linux more命令详解
    Linux mktemp命令
    MySQL状态变量详解
    mysql性能分析show profile/show profiles
    MySQL执行计划
  • 原文地址:https://www.cnblogs.com/huj690/p/4562257.html
Copyright © 2011-2022 走看看