(相关资料图)

1 问题

int data;struct List* next;}LIST;//表的初始化,不带头节点,LIST* CreatSlist() { LIST* head=NULL; for(int i=5;i>=1;i--) {LIST* newhead=(LIST *)malloc(sizeof(LIST));newhead->data=i; newhead->next=head; head=newhead;}return head;}//打印输出 void print(LIST* P){while(P!=NULL){printf("%d ",P->data);P=P->next;}printf("\n");return; }//单链表反转(头插法) LIST* reverse(LIST* head){LIST *temp=NULL,*Phead=NULL; while(head!=NULL){temp=head;head=head->next;temp->next=Phead;Phead=temp;}return Phead; } int main (){printf("原来的链表的数据:\n"); LIST* P=CreatSlist();print(P);printf("反转后链表的数据:\n"); LIST* head=reverse(P);print(head);return 0; } #方法二#include #include typedef struct List{int data;struct List* next;}LIST;//表的初始化,不带头节点,LIST* CreatSlist() { LIST* head=NULL; for(int i=5;i>=1;i--) {LIST* newhead=(LIST *)malloc(sizeof(LIST));newhead->data=i; newhead->next=head; head=newhead;}return head;}//打印输出 void print(LIST* P){while(P!=NULL){printf("%d ",P->data);P=P->next;}printf("\n");return; }//单链表反转(递归法) LIST* reverse(LIST* head){if(head==NULL||head->next==NULL)return head;LIST *new_head=reverse(head->next);head->next->next=head;head->next=NULL;return new_head; } int main (){printf("原来的链表的数据:\n"); LIST* P=CreatSlist();print(P);printf("反转后链表的数据:\n"); LIST* head=reverse(P);print(head);return 0; }

3 结语

针对如何实现单链表的逆置,提出利用头插法和递归法进行处理,通过利用IDLE编写,证明该方法是有效的,通过本次实验加深单链表基本处理操作,为更深入的有关单链表的操作积累了经验,有助于提升对单链表的操作能力。

推荐内容