zoukankan      html  css  js  c++  java
  • 数据结构:单向链表系列8--反转链表

    业务需求:给定一个指向头指针的链表,反转链表。实现过程:更改相邻节点之间的链域。

    例:

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

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

    输入: NULL
    输出: NULL

    输入: 1->NULL
    输出: 1->NULL

    迭代法:

    空间复杂度:O(1),时间复杂度:O(n)

    1、初始化3个指针

    pre = NULL, curr = *head, next = NULL

    2、迭代列表,执行以下循环

    // Before changing next of current,
    // store next node
    next = curr->next

    // Now change next of current
    // This is where actual reversing happens
    curr->next = prev

    // Move prev and curr one step forward
    prev = curr
    curr = next

    以下是算法实现过程:

    // Iterative C program to reverse a linked list
    #include <stdio.h>
    #include <stdlib.h>
    
    /* Link list node */
    struct Node
    {
        int data;
        struct Node* next;
    };
    
    /* function to reverse the linked list */
    void reverse(struct Node** head_ref)
    {
        struct Node* prev = NULL;
        struct Node* current = *head_ref;
        struct Node* next = NULL;
    
        while(current != NULL)
        {
            //Store next
            next = current->next;
    
            //Reverse current node's pointer
            current->next = prev;
    
            //Move pointers one position ahead.
            prev = current;
            current = next;
        }
        *head_ref = prev;
    }
    
    /* function to push a node */
    void push(struct Node** head_ref, int new_data)
    {
        struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
        new_node->data = new_data;
        new_node->next = (*head_ref);
        (*head_ref) = new_node;
    }
    
    
    /* function to print linked list */
    void printList(struct Node* head)
    {
        struct Node* temp = head;
        while(temp != NULL)
        {
            printf("%d ", temp->data);
            temp = temp->next;
        }
        printf("
    ");
    }
    
    /* driver program to test above function */
    int main() {
    
        /* Start with the empty list */
        struct Node* head = NULL;
    
        push(&head, 20);
        push(&head, 4);
        push(&head, 15);
        push(&head, 85);
    
        printf("Given linked list
    ");
        printList(head);
        reverse(&head);
        printf("Reversed linked list
    ");
        printList(head);
    
        return 0;
    }

    文章来源:https://www.geeksforgeeks.org/reverse-a-linked-list/

  • 相关阅读:
    四则运算 calc()
    如何创建width与height比例固定的元素
    eslint规则 中文备注
    使用gulp构建工具
    JavaScript 给表格排序
    【转】grunt动态生成文件名
    vim正则表达式(转)
    正则表达式30分钟入门教程(转)
    hdu 1874 Dijkstra算法
    centos7.4安装mysql
  • 原文地址:https://www.cnblogs.com/passedbylove/p/11442956.html
Copyright © 2011-2022 走看看