思路就是這樣啊棧的特點就是先進後出所以完全可以用單向連結串列來模擬,只要是pop、push函式正確就可以所以這個問題就可以簡化為單向連結串列反轉的問題了兩種方式非遞迴pQueueconverse(pQueue t){tp p1, p2, tmp;int flag = 0;p2 = t->next->next;p1 = t;while(1){p1->next->next = p1;p1 = p1->next;if(p1->next == t){p1->next->next = NULL;}else{p1->next->next = tmp;}tmp = p1;if( p2->next == NULL ){p2->next = p1;break;}if ( p2->next->next == NULL ){p2->next->next = p2;p2 = p2->next;p2->next->next = p1;break;}p1 = p2;p2 = p2->next->next;}return p2;}遞迴:pQueue transposeQueue(pQueue phead){pQueue tmp = phead;if(tmp->next != NULL){transposeQueue(tmp->next)->next = tmp;tmp->next = NULL;}else{head = tmp;}return tmp;}struct queue{int data;struct queue *next;};typedef struct queue *pQueue;typedef struct queue queue;
思路就是這樣啊棧的特點就是先進後出所以完全可以用單向連結串列來模擬,只要是pop、push函式正確就可以所以這個問題就可以簡化為單向連結串列反轉的問題了兩種方式非遞迴pQueueconverse(pQueue t){tp p1, p2, tmp;int flag = 0;p2 = t->next->next;p1 = t;while(1){p1->next->next = p1;p1 = p1->next;if(p1->next == t){p1->next->next = NULL;}else{p1->next->next = tmp;}tmp = p1;if( p2->next == NULL ){p2->next = p1;break;}if ( p2->next->next == NULL ){p2->next->next = p2;p2 = p2->next;p2->next->next = p1;break;}p1 = p2;p2 = p2->next->next;}return p2;}遞迴:pQueue transposeQueue(pQueue phead){pQueue tmp = phead;if(tmp->next != NULL){transposeQueue(tmp->next)->next = tmp;tmp->next = NULL;}else{head = tmp;}return tmp;}struct queue{int data;struct queue *next;};typedef struct queue *pQueue;typedef struct queue queue;