鏈表元素的反轉(叠代法)
阿新 • • 發佈:2018-08-24
指針 sca code 地址 div stdio.h all can ret
#include<stdio.h> #include<stdlib.h> struct symbol{ char sym; struct symbol *nextPtr; }; struct symbol *createsym(struct symbol *p); void listsym(struct symbol *p); struct symbol *reversesym(struct symbol *p); int main(){ struct symbol *head; head=NULL; head=createsym(head); listsym(head); head=reversesym(head); listsym(head); return 0; } struct symbol *createsym(struct symbol *p){ //p=(struct symbol *)malloc(sizeof(struct symbol)); struct symbol *p1,*p2; p1=p2=(struct symbol*)malloc(sizeof(struct symbol)); printf("請輸入字符串以enter結束:\n"); scanf("%c",&p1->sym); p1->nextPtr=NULL; p=p1; while(p1->sym!=‘\n‘){ p2=p1; p1=(struct symbol *)malloc(sizeof(struct symbol)); scanf("%c",&p1->sym); p1->nextPtr=NULL; p2->nextPtr=p1; } printf("輸入完成!\n"); return p; } void listsym(struct symbol *p){if(!p){ printf("字母鏈表為空!\n"); }else{ printf("字母序列為:\n"); while(p){ printf("%c",p->sym); p=p->nextPtr; } } } struct symbol *reversesym(struct symbol *p){//叠代法反轉 if(!p||p->nextPtr==NULL){ return p; } struct symbol *newhead=NULL,*temp; while(p){ temp=p->nextPtr;//保存p的下一個地址 p->nextPtr=newhead;//指向新頭部 newhead=p;//前移newhead指針 p=temp;//前移p指針 } printf("reverse complete.\n"); return newhead; };
鏈表元素的反轉(叠代法)