数据结构:单向链表系列8--反转链表

Posted passedbylove

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构:单向链表系列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("\\n");


/* 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\\n");
    printList(head);
    reverse(&head);
    printf("Reversed linked list\\n");
    printList(head);

    return 0;

 

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

以上是关于数据结构:单向链表系列8--反转链表的主要内容,如果未能解决你的问题,请参考以下文章

反转单向链表(JAVA)

链表的java实现(单向双向链表,单向链表的反转)

链表的java实现(单向双向链表,单向链表的反转)

反转单向双向链表

5定义一个JS函数,反转单向链表

Java实现单向链表反转