C语言反转链表程序
在这个问题中,我们给定一个链表。我们的任务是创建一个反转链表的程序。
该程序将反转给定的链表并返回反转后的链表。
链表是由包含项目的链接组成的序列。每个链接都包含到另一个链接的连接。
示例
9 -> 32 -> 65 -> 10 -> 85 -> NULL
反转链表是通过反转链表的链接来形成链表的链表。链表的头节点将成为链表的最后一个节点,最后一个节点将成为头节点。
示例
从上述链表形成的反转链表 -
85 -> 10 -> 65 -> 32 -> 9 -> NULL
为了反转给定的链表,我们将使用三个额外的指针,它们将在过程中使用。这些指针将是 previous、after、current。
我们将 initially previous 和 after 初始化为 NULL,并将 current 初始化为链表的头。
在此之后,我们将迭代直到到达初始(非反转链表)的 NULL。并执行以下操作:
after = current -> next current -> next = previous previous = current current = after
现在让我们创建一个反转链表的程序。创建程序的方法有两种,一种是迭代的,另一种是递归的。
反转链表程序(尾递归方法)
示例
#include <stdio.h>
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("
");
}
int main(){
Node* head1 = insertNode(9);
head1->next = insertNode(32);
head1->next->next = insertNode(65);
head1->next->next->next = insertNode(10);
head1->next->next->next->next = insertNode(85);
printf("Linked list : \t");
printLinkedList(head1);
tailRecReveseLL(&head1);
printf("Reversed linked list : \t");
printLinkedList(head1);
return 0;
}输出
Linked list : 9 32 65 10 85 Reversed linked list : 85 10 65 32 9
反转链表程序(迭代方法)
示例
#include <stdio.h>
struct Node {
int data;
struct Node* next;
Node(int data){
this->data = data;
next = NULL;
}
};
struct LinkedList {
Node* head;
LinkedList(){
head = NULL;
}
void interReverseLL(){
Node* current = head;
Node *prev = NULL, *after = NULL;
while (current != NULL) {
after = current->next;
current->next = prev;
prev = current;
current = after;
}
head = prev;
}
void print() {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp-> data);
temp = temp->next;
}
printf("
");
}
void push(int data){
Node* temp = new Node(data);
temp->next = head;
head = temp;
}
};
int main() {
LinkedList linkedlist;
linkedlist.push(85);
linkedlist.push(10);
linkedlist.push(65);
linkedlist.push(32);
linkedlist.push(9);
printf("Linked List : \t");
linkedlist.print();
linkedlist.interReverseLL();
printf("Reverse Linked List : \t");
linkedlist.print();
return 0;
}输出
Linked List : 9 32 65 10 85 Reverse Linked List : 85 10 65 32 9
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP