c_cpp FP风格的反向单链表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp FP风格的反向单链表相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
typedef struct SinglyLinkedListNode {
int value;
struct SinglyLinkedListNode* next;
} SinglyLinkedListNode;
SinglyLinkedListNode* reverseSinglyLinkedList(SinglyLinkedListNode* list);
SinglyLinkedListNode* reverseSinglyLinkedListHelper(SinglyLinkedListNode* listToReverse, SinglyLinkedListNode* listToAppend);
SinglyLinkedListNode* reverseSinglyLinkedList(SinglyLinkedListNode* list) {
return reverseSinglyLinkedListHelper(list, NULL);
}
SinglyLinkedListNode* reverseSinglyLinkedListHelper(SinglyLinkedListNode* listToReverse, SinglyLinkedListNode* listToAppend) {
if (listToReverse == NULL) {
return listToAppend;
}
else {
SinglyLinkedListNode* firstToReverse = listToReverse;
SinglyLinkedListNode* restToReverse = firstToReverse->next;
firstToReverse->next = listToAppend;
return reverseSinglyLinkedListHelper(restToReverse, firstToReverse);
}
}
int main() {
SinglyLinkedListNode* singlyLinkedList = NULL;
for (int i = 0; i < 5; i++) {
SinglyLinkedListNode* newNode = (SinglyLinkedListNode*)malloc(sizeof(SinglyLinkedListNode));
newNode->value = i;
newNode->next = singlyLinkedList;
singlyLinkedList = newNode;
}
singlyLinkedList = reverseSinglyLinkedList(singlyLinkedList);
SinglyLinkedListNode* currNode = singlyLinkedList;
for (int i = 0; i < 5; i++) {
if (currNode->value != i) {
printf("error\n");
}
currNode = currNode->next;
}
return 0;
}
以上是关于c_cpp FP风格的反向单链表的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 单链表的快速排序
c_cpp 用于检查单链表是否为回文的功能
c_cpp 单链表中的替代奇数和偶数节点
c_cpp C中的单链表 - 现在只实现交换
数据结构之单链表反向查找
单链表 C 反向数据读取