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