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

    快慢指针是链表中常用的技巧,反转链表也是常用算法之一。
    使用p和q两个指针配合工作,使得两个节点间的指向反向,同时用r记录剩下的链表。

    p = head;
    q = head->next;
    这里写图片描述
    head->next = NULL;
    这里写图片描述
    现在进入循环体,这是第一次循环。
    r = q->next;
    q->next = p;
    这里写图片描述
    p = q;
    q =r;
    这里写图片描述
    第二次循环。
    r = q->next
    这里写图片描述
    q->next = p;
    这里写图片描述
    p = q;
    这里写图片描述
    q = r
    这里写图片描述
    第三次循环。。。。。

    具体代码如下:

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode* pre = NULL;
            while (head) {
                ListNode* next = head -> next;
                head -> next = pre;
                pre = head;
                head = next;
            } 
            return pre;
        }
    };

    反转链表还可以采用头插法

    /**
     * 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) {
            //头插法
            if(!head || !head->next) return head;
            ListNode* dummy = new ListNode(-1);
            dummy->next = head;
            ListNode* pre = head;
            ListNode* cur = head->next;
            while(cur){
                pre->next = cur->next;
                cur->next = dummy->next;
                dummy->next = cur; //插入头部
                cur = pre->next;
            }
            return dummy->next;
        }
    };
  • 相关阅读:
    Zend Studio 9.0.2破解文件和注册码下载
    shell之netstat命令
    shell之arp命令
    Linux网络运维相关
    Linux静态ip设置及一些网络设置
    shell之进程
    shell之小知识点
    软连接与硬链接
    shell之dialog提示窗口
    Linux特殊权限位
  • 原文地址:https://www.cnblogs.com/CarryPotMan/p/5343682.html
Copyright © 2011-2022 走看看