(数据结构)线性表_单链表反转 _模仿

来源:互联网 发布:改图宝软件下载 编辑:程序博客网 时间:2024/05/16 11:35

方法1:

#include<stdio.h>   #include<stdlib.h>   #include<malloc.h>   typedef int ElemType;    typedef struct Node *List;typedef struct Node *Position;typedef struct Node Node;struct Node{ElemType Element;List next;};int length_List(List L)  //L带头结点{int len;    Position temp;  temp=L;while(temp->next!=NULL){temp=temp->next;len++;}return len;}List ReverseList(List L)  //反转单链表函数,L带头结点{if(L->next->next==NULL||L->next==NULL)  //空链表或者只有一个结点return L;List Result ,temp;  //使用这两个结构体变量,起保护L作用int len ,i;Result=(List)malloc(sizeof(Node));      Result->next=NULL;    len=length_List(L);for(i=0;i<len;i++){        temp=(List)malloc(sizeof(Node)); temp->Element=L->next->Element;  //临时链表结点,用来存放L链表中的元素temp->next=Result->next;        Result->next=temp;        L=L->next;}return Result;}

方法2:

#include<stdio.h>   #include<stdlib.h>   #include<malloc.h>   typedef int ElemType;    typedef struct Node *List;typedef struct Node *Position;typedef struct Node Node;struct Node{ElemType Element;List next;};List ReverseList(List L1)  //反转单链表函数,L1带头结点{if(L1->next==NULL||L1->next->next==NULL)return L1;Position PreviousPos ,CurrentPos ,NextPos;  List L;L=L1->next;  //L无头结点,为处理方便PreviousPos=NULL;CurrentPos=L;NextPos=L->next;while(NextPos!=NULL){CurrentPos->next=PreviousPos;PreviousPos=CurrentPos;CurrentPos=NextPos;NextPos=NextPos->next;}    CurrentPos->next=PreviousPos;return CurrentPos;}
0 0
原创粉丝点击