C language to achieve a single linked list of reverse order and reverse output instances
- 2020-04-02 02:40:35
- OfStack
The reverse output of a single linked list can be divided into two cases. The other is to reverse the list. This article illustrates the two methods with examples. The details are as follows:
1. Output in reverse order
Example code is as follows:
#include<iostream>
#include<stack>
#include<assert.h>
using namespace std;
typedef struct node{
int data;
node * next;
}node;
//Add a tail
node * add(int n, node * head){
node * t = new node;
t->data = n;
t->next = NULL;
if (head == NULL){
head = t;
}
else if (head->next == NULL){
head->next = t;
}
else{
node * p = head->next;
while (p->next != NULL){
p = p->next;
}
p->next = t;
}
return head;
}
//Order of the output
void print(node * head){
node * p = head;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//recursive
void reversePrint(node * p){
if (p != NULL){
reversePrint(p->next);
cout << p->data << " ";
}
}
//The stack
void reversePrint2(node * head){
stack<int> s;
while (head != NULL){
s.push(head->data);
head = head->next;
}
while (!s.empty()){
cout << s.top() << " ";
s.pop();
}
}
int main(){
node * head = NULL;
for (int i = 1; i <= 5; i++){
head = add(i, head);
}
print(head);
reversePrint(head);
reversePrint2(head);
system("pause");
return 0;
}
Output in reverse order can be done in three ways: recursion, stack, and output in reverse order. The last one I'm going to talk about.
2. Reverse order of single linked list
Example code is as follows:
#include<iostream>
#include<stack>
#include<assert.h>
using namespace std;
typedef struct node{
int data;
node * next;
}node;
node * add(int n, node * head){
node * t = new node;
t->data = n;
t->next = NULL;
if (head == NULL){
head = t;
}
else if (head->next == NULL){
head->next = t;
}
else{
node * p = head->next;
while (p->next != NULL){
p = p->next;
}
p->next = t;
}
return head;
}
//cycle
node * reverse(node * head){
if (head == NULL || head->next == NULL){
return head;
}
node * p1 = head;
node * p2 = head->next;
node * p3 = NULL;
head->next = NULL;
while (p2 != NULL){
p3 = p2;
p2 = p2->next;
p3->next = p1;
p1 = p3;
}
head = p1;
return head;
}
void print(node * head){
node * p = head;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//recursive
node * reverse2(node * p){
if (p == NULL || p->next == NULL){
return p;
}
node * newHead = reverse2(p->next);
p->next->next = p;
p->next = NULL;
return newHead;
}
int main(){
node * head = NULL;
for (int i = 1; i <= 5; i++){
head = add(i, head);
}
print(head);
head = reverse(head);
print(head);
head = reverse2(head);
print(head);
system("pause");
return 0;
}
There are two ways to reverse the list: loop and recursion. The easiest way for the reader to understand is to draw it on paper.
I hope the examples described in this paper can be helpful to the learning of data structure and algorithm.