C語言實現連結串列的逆置
//演算法關鍵:將頭節點後的節點移到頭結點之前,並使最前面的節點為頭結點
#include<stdio.h> #include<malloc.h> #define LEN sizeof(struct LNode)
struct LNode { int data; struct LNode *next; };
struct LNode *creat() {struct LNode *head,*p1,*p2; p1=p2=(struct LNode * )malloc(LEN); int n=0; printf("請依次輸入連結串列1的資料,輸入0時結束:\n"); scanf("%d",&p1->data); head=NULL; while(p1->data!=0) {n++; if(n==1)head=p1; else p2->next=p1; p2=p1; p1=(struct LNode *)malloc(LEN); scanf("%d",&p1->data); } p2->next=NULL; return(head); }
void print(struct LNode *head) { struct LNode *p; printf("逆置後的連結串列為:\n"); p=head; if(head!=NULL) { while(p!=NULL) {printf("%d\n",p->data); p=p->next; } } }
int main() {struct LNode *head,*p1,*p2; p1=p2=head=creat(); while((p2->next)!=NULL) { p2=p2->next; p1->next=p2->next; p2->next=head; head=p2; p2=p1; } print(head); return 0; }