程序笔记   发布时间:2022-05-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C语言实现单链表逆序与逆序输出实例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

单链表的逆序输出@R_388_6962@,一种是只逆序输出,实际上不逆序;另一种是把链表逆序。本文就分别实例讲述一下两种方法。具体如下:

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;
 for (int i = 1; i <= 5; i++){
  head = add(i,head);
 }
  print(head);
  reversePrint(head);
  reversePrint2(head);
 system("pause");
  return 0;
}

逆序输出可以用三种方法: 递归,栈,逆序后输出。最后一种接下来讲到。

2.单链表逆序

实例代码如下:

#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;
}

//循环
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;
}


//递归
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;
}

这里链表逆序用了两种方法:循环,递归。读者最容易理解的方法就是在纸上自己画一下。

希望本文所述实例对大家的数据结构与算法学习能有所帮助。

您可能感兴趣的文章:

  • C语言之单链表的插入、删除与查找
  • C语言单链表常见操作汇总
  • c语言实现单链表算法示例分享
  • C语言单链表实现多项式相加
  • C语言单链表的实现
  • 数据结构 C语言实现循环单链表的实例
  • C语言实现学生信息管理系统(单链表)
  • C语言实现单链表实现方法
  • C语言单链表版学生信息管理系统
  • C语言单链表实现方法详解

大佬总结

以上是大佬教程为你收集整理的C语言实现单链表逆序与逆序输出实例全部内容,希望文章能够帮你解决C语言实现单链表逆序与逆序输出实例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。