假设链表为:1 2 3 4
现在需要把链表反向,变为:4 3 2 1
利用迭代法:
void node_reverse(Node** head)
{
Node* p_prev = NULL;
Node* p_curr = *head;
Node* p_next = NULL;
while (p_curr != NULL) {
p_next = p_curr->next;
p_curr->next = p_prev;
p_prev = p_curr;
p_curr = p_next;
}
*head = p_prev;
}
首先:假设各个节点地址为 150、200、125、100
那么最开始数据形式如下图
while()第一次运行完成后:变成下图
while()第二次运行完成后:变成下图
while()第三次运行完成后:变成下图
while()第四次运行完成后:变成下图 退出循环
最后把头结点指向p_prev,变成下图
即:
添加Node 定义、node_add()、node_print()
//node.h
#ifndef _NODE_H_
#define _NODE_H_
typedef struct Node
{
int data;
struct Node* next;
}Node;
/**
* @brief 链表添加数据,尾插法
* @param[in] head 链表
* @param[in] data 需要添加的数据
* @param[out] 1 :添加成功 0:添加失败
*/
int node_add(Node **head, int data);
/**
* @brief 链表遍历
* @param[in] head 链表
*/
void node_print(Node *head);
/**
* @brief 链表遍历
* @param[in] head 链表
*/
void node_reverse(Node** head);
#endif /* ! _NODE_H_ */
//node.c
#include <stdlib.h>
#include <stdio.h>
#include "node.h"
/**
* @brief 链表添加数据,尾插法
* @param[in] head 链表
* @param[in] data 需要添加的数据
* @param[out] 1 :添加成功 0:添加失败
*/
int node_add(Node **head, int data)
{
Node* temp = (Node*)malloc(sizeof(Node));
if (temp == NULL) {
return NULL;
}
temp->data = data;
temp->next = NULL;
if (*head == NULL) {
*head = temp;
return 1;
}
Node* p_prev = *head;
while (p_prev->next) {
p_prev = p_prev->next;
}
p_prev->next = temp;
return 1;
}
/**
* @brief 链表遍历
* @param[in] head 链表
*/
void node_print(Node* head)
{
Node* temp = head;
printf("List is:");
while (temp) {
printf(" %d", temp->data);
temp = temp->next;
}
printf("\n");
}
/**
* @brief 链表反向
* @param[in] head 链表
*/
void node_reverse(Node** head)
{
Node* p_prev = NULL;
Node* p_curr = *head;
Node* p_next = NULL;
while (p_curr) {
p_next = p_curr->next;
p_curr->next = p_prev;
p_prev = p_curr;
p_curr = p_next;
}
*head = p_prev;
return ;
}
然后在main()函数中进行测试
#include <stdio.h>
#include "node.h"
int main()
{
Node *head = NULL;
node_add(&head, 1);
node_add(&head, 2);
node_add(&head, 3);
node_add(&head, 4);
node_print(head);
node_reverse(&head);
node_print(head);
return 0;
}
运行结果: