zoukankan      html  css  js  c++  java
  • 反转链表

    反转一个链表

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    思路:首先此链表没有头节点,只有下一个节点,所以我们在分析的时候要想方法通过下一个节点的指向来达到反转效果,

    迭代方法:

     //伪代码:
     /**
      * Definition for singly-linked list.
      * struct ListNode {
      *     int val;
      *     ListNode *next;
      *     ListNode(int x) : val(x), next(NULL) {}
      * };
      */
     class Solution {
     public:
         ListNode* reverseList(ListNode* head) {
             while(head==NULL||head->next==NULL)
                  return head;
             ListNode* p=NULL;
             while(head){
             ListNode* temp=head->next;
             head->next=p;
             p=head;
             head=temp;
             }
                  return p;       
         }
     };

    递归方法:

    //伪代码
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            while(head==NULL||head->next==NULL)
                return head;
            ListNode* newnode =reverseList(head->next);
            head->next->next=head;
            head->next=NULL;
            return newnode;
        }
    };

    学习常言:户枢不蠹,流水不腐

  • 相关阅读:
    数据压缩和归档
    数据持久化
    文件和目录的使用
    数据及数据处理
    data types
    string services
    logging模块
    指导
    比较两个NSDate类型的参数相差的时间差
    推送 iOS 10
  • 原文地址:https://www.cnblogs.com/yunianzeng/p/10863238.html
Copyright © 2011-2022 走看看