链表反向实现

链表的实现很简单,但有一个注意事项,在插入链表时,如果定义了一个Node* head,那么Insert函数的形参应该为(Node**),否则无法对head进行修改,就算我把head定义为全局变量也是如此。如果head是一个局部变量的话那么很容易理解,但为何定义为全局变量也是如此呢?我没有在main函数中定义局部变量head,整个文件只有一个全局变量head。

接着我又学习了链表反转,我学习了两种方法,一种是迭代型,另一种是递归型,在我动手实现这两种方式后,我惊讶的发现:迭代型必须得用一个二级指针才能正确的反转链表,但是递归型的参数仅需要一个一级指针就可以实现,因此我对此很疑惑,有点打破我之前对于C语言指针和内存的理解了。

这是我的代码

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

typedef struct Node* Link;
typedef struct Node NNode;
Link head;


int Insert(Link* head, int value) {
NNode* temp = (NNode*)malloc(sizeof(NNode));
NNode* cur = head;
temp->data = value;
temp->next = NULL;
if(head == NULL) {
head = temp;
return 1;
}
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = temp;

return 1;
}

void Print(Link head) {
NNode
node = head;
if(head == NULL) {
printf(“head is null\n”);
return;
}
while (node != NULL)
{
printf(“%d\n”, node->data);
node = node->next;
}
return;
}

void Reverse(Link
head) {
NNode
prev = NULL;
NNode* cur = head;
NNode
next = NULL;

if(*head == NULL)
{
printf(“head is null\n”);
return;
}
while(cur != NULL)
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*head = prev;
}

void Recursion_Reverse(Link p) {
if(p == NULL)
return;
if(p->next == NULL)
{
head = p;
return;
}
Recursion_Reverse(p->next);
p->next->next = p;
p->next = NULL;
}

int main() {
Insert(&head, 1);
Insert(&head, 2);
Insert(&head, 3);
Insert(&head, 4);
Print(head);
Reverse(&head);
Print(head);
Recursion_Reverse(head);
Print(head);

return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值