反转链表的C程序
在这个问题中,我们给出了一个链表。我们的任务是创建一个程序来反转链表。
该程序将反转给定的链表并返回反转后的链表。
链表是一个包含项目的链接序列。每个链接包含到另一个链接的连接。
示例
9 -> 32 -> 65 -> 10 -> 85 -> NULL登录后复制
示例
从上述链表中形成的反转链表 −
85 -> 10 -> 65 -> 32 -> 9 -> NULL登录后复制
我们将初始时将previous和after都设置为NULL,将current设置为链表的头部。
在此之后,我们将迭代直到达到初始链表的NULL。然后执行以下操作:
after = current -> next current -> next = previous previous = current current = after登录后复制
反转链表的程序(尾递归方法)
示例
演示
#include struct Node { int data; struct Node* next; }; Node* insertNode(int key) { Node* temp = new Node; temp->data = key; temp->next = NULL; return temp; } void tailRecRevese(Node* current, Node* previous, Node** head){ if (!current->next) { *head = current; current->next = previous; return; } Node* next = current->next; current->next = previous; tailRecRevese(next, current, head); } void tailRecReveseLL(Node** head){ if (!head) return; tailRecRevese(*head, NULL, head); } void printLinkedList(Node* head){ while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("