单链表逆置

来源:互联网 发布:微软编程一小时 编辑:程序博客网 时间:2024/06/05 14:52

3、写一算法,将单链表就地逆置。

#include<stdio.h>#include<stdlib.h>#include<malloc.h>typedef struct node{    int data;struct node *next;}Node;void Init_Node(Node *node);Node* Create_List(int listLength);void Reverse(Node *head);void Print(Node *head);void main(){Node *listA;    listA=Create_List(5);printf("原来的单链表的数据元素为:");Print(listA);    Reverse(listA);printf("重置完毕后的单链表的数据元素为:");Print(listA);printf("程序运行完毕\n");}void Init_Node(Node *node){node->next=NULL;node->data=0;}Node* Create_List(int listLength){printf("正在申请一个长度为%d的带头结点的单链表\n",listLength);Node *head,*tail,*newNode;int data;head=(Node *)malloc(sizeof(Node));if(head==NULL) {printf("申请内存失败\n");return NULL;}    tail=head;tail->next=NULL;int i=1;    while(listLength--){    newNode=(Node *)malloc(sizeof(Node));Init_Node(newNode);printf("请输入第%d个节点的数据",i++);        scanf("%d",&data);newNode->data=data;tail->next=newNode;tail=newNode;}return head;printf("单链表创建完毕");}                                                                                           void Reverse(Node *head)                                                                                                                                              {                                                                                                                                                      Node *p,*q;    p = head->next;            head->next = NULL;          while(p != NULL){           q = p->next;              p->next = head->next;           head->next = p;        p = q;    }}void Print(Node *head){    Node *node;node=head->next;int i=0;while(node!=NULL){    printf("%d  ",node->data);node=node->next;i++;if(i==10)break;}printf("Print完毕\n");}


原创粉丝点击