1. 程式人生 > 其它 >簡單c語言 遞迴 逆轉 連結串列

簡單c語言 遞迴 逆轉 連結串列

技術標籤:單鏈表

#include<stdio.h>
#include<stdlib.h>
typedef struct Node{ 
    int data; 
    struct Node* next; 
}node;

node* create(int n)//假設有n個節點
{
	node* p = NULL;
	node* head =NULL; 
	int i = 1; 
    while(i <= n)
	{ 
	    if(!head){
  		    head = p =(node*)malloc(sizeof(struct Node)
); printf("p->data=\t"); scanf("%d",&p->data);//賦值 p->next = NULL; }else{ p->next = (node*)malloc(sizeof(struct Node)); printf("p->data=\t"); scanf("%d",&p->next->
data);//賦值 p->next->next = NULL; p = p->next; } ++i; } return head; } node* reverse(node* p)//利用遞迴方法解決逆轉 { node* p1; if(!p){ return NULL; }else{ if(p->next != NULL){ p1 = reverse(p->next);//不斷呼叫返回逆轉後的節點 p->next->next = p; //逆轉 p->
next = NULL; // 善後 return p1; }else{ return p; } } } int main() { int n; printf("請輸入您需要輸入幾個元素:\t"); scanf("%d",&n); node* p = create(n); node* y = reverse(p); printf("------------------------------------\n"); while(y!=NULL){ printf("y->data=%9d\n",y->data); y=y->next; } }