当前位置: 编程技术>c/c++/嵌入式
C语言实现单链表逆序与逆序输出实例
来源: 互联网 发布时间:2014-10-27
本文导语: 单链表的逆序输出分为两种情况,一种是只逆序输出,实际上不逆序;另一种是把链表逆序。本文就分别实例讲述一下两种方法。具体如下: 1.逆序输出 实例代码如下: #include #include #include using namespace std; typedef struct no...
单链表的逆序输出分为两种情况,一种是只逆序输出,实际上不逆序;另一种是把链表逆序。本文就分别实例讲述一下两种方法。具体如下:
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 data); head = head->next; } while (!s.empty()){ cout 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