单向链表反转

单向链表反转

 

单向链表反转实现思路:

(1)从头节点开始,此时头节点为当前节点,反转当前节点所指向的下个节点

(2)移动当前节点到下一个节点,即下一个相邻节点为新的当前节点

(3)循环迭代上述步骤1、2,迭代次数为链表长度

参考博文链接:https://www.cnblogs.com/passedbylove/p/11442606.html

 

该思路演示框图如下,以链表长度为4举例说明

 

代码详情如下

// 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;
}

 

程序运行结果

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值