zoukankan      html  css  js  c++  java
  • 带头结点的单链表反转

    struct Node {
        int data;
        Node *next;
    };

    方法一:就地逆序

    主要思路:在遍历链表的时候,修改当前结点的指针域的指向,让其指向前驱结点。
    为此,需要用三个指针变量分别指向当前结点、前驱结点、后继结点。遍历完所有的结点后,即可以完成指针的逆序。最后,让头节点的指针域指向原来最后一个元素结点。
    void reverse(Node* head) {
    if (head == NULL||head->next == NULL) return;
    Node
    * pre = NULL; Node* cur = head->next; Node* next;
    while (cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } head->next = pre; }

    方法二:插入法

    主要思路:从链表的第二个结点开始,把遍历到的结点插入到头结点的后面,直到遍历结束。
    void reverse(Node* head) {
    
        if (head == NULL||head->next == NULL) return;
    
        Node *cur, *next;
        cur = head->next->next;//cur初始指向第二个结点(不包括头结点)
        head->next->next = NULL;
    
    
        while (cur) {
            next = cur->next;
            cur->next = head->next;
            head->next = cur;
            cur = next;
        }    
    }

    方法三:原地递归反转

    主要思路:我们使用递归的原理是每次调用函数让他的头指针向后走,直到走到尾节点,我们将尾节点作为头,然后递归回去相当于我们倒着访问了这个单链表
    Node* reverse(Node* head){
        //返回反转链表的首元结点的地址
        if (head == NULL || head->next == NULL)
            return head;
    Node
    * newhead = reverse(head->next); // 先反转后面的链表 head->next->next = head;//再将当前节点(head)设置为其然来后面节点(head->next)的后续节点 head->next = NULL; return newhead; // 此处返回的newhead,永远指向反转后链表的首元节点,不随着回朔而变化。 }
  • 相关阅读:
    java代码中的三元表达式
    RequestDispatcher用法
    SQL的分页算法
    “将截断字符串或二进制数据”错误分析
    SQL Server 2005中top关键字的用法
    rtems开发环境
    linux虚拟机无法识别u盘
    多核性能优化
    windows无法安全卸载u盘的老毛病
    关闭指定servcie日志
  • 原文地址:https://www.cnblogs.com/fuqia/p/10260342.html
Copyright © 2011-2022 走看看