C语言实现单链表逆序与逆序输出实例语言实现单链表逆序与逆序输出实例
主要介绍了C语言实现单链表逆序与逆序输出,是数据结构与算法中比较基础的重要内容,有必要加以牢固掌握,需
要的朋友可以参考下
单链表的逆序输出分为两种情况,一种是只逆序输出,实际上不逆序;另一种是把链表逆序。本文就分别实例讲述一下两种方
法。具体如下:
1.逆序输出逆序输出
实例代码如下:
#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;
}
//顺序输出
void print(node * head){
node * p = head;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//递归
void reversePrint(node * p){
if (p != NULL){
reversePrint(p->next);
cout << p->data << " ";
}
}
//栈
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;