• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C语言实现单链表逆序与逆序输出实例

c语言 搞代码 4年前 (2022-01-06) 27次浏览 已收录 0个评论

这篇文章主要介绍了C语言实现单链表逆序与逆序输出,是数据结构与算法中比较基础的重要内容,有必要加以牢固掌握,需要的朋友可以参考下

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

1.逆序输出

实例代码如下:

 #include #include #include 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 <data <next; } cout <next); cout <data << " "; } } //栈 void reversePrint2(node * head){ stack 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 #include<div style="color:transparent">来源gaodai.ma#com搞##代!^码@网</div> #include 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 <data <next; } cout <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语言实现单链表逆序与逆序输出实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C语言实现单链表逆序与逆序输出实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址