数据结构:单向链表系列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/

猜你喜欢

转载自www.cnblogs.com/passedbylove/p/11442956.html