链表逆序问题
给定一个单向链表typedef struct list
{
int m_data;
struct list* m_next;
}Link;
写一个函数逆序输出链表;
我的想法比较笨,先遍历一遍链表,把链表里的数存到数组里,在逆向输出数组里的数。
用堆栈怎么处理?用递归又怎么处理?
#include <stdio.h> typedef struct node_ { int data; struct node_* next; } node; void list_print( const node* head ) { for( ; head; head=head->next ) printf( "%d%c", head->data, " \n"[head->next==NULL] ); } node* list_reverse( node* head ) { node* pre = NULL; for( ; head; ) { node* tmp = head->next; head->next = pre; pre = head; head = tmp; } return pre; } int main( void ) { node a[3] = { {0,a+1}, {1,a+2}, {2,NULL} }; node* head = &a[0]; list_print( head ); head = list_reverse( head ); list_print( head ); }
[此贴子已经被作者于2020-4-16 10:55编辑过]