1 題目描述
定義一個函數,輸入一個鏈表的頭結點,反轉該鏈表並輸出反轉後鏈表的頭結點。
2 解題方法
頭結點:不屬於鏈表中有效的元素,爲了方便操作而設立的一個節點
運用頭插法將鏈表重寫插入到頭結點
具體操作如下所示:
3 C 語言實現
#include<stdio.h>
typedef int ElemType;
typedef struct node{
ElemType data;
struct node* next;
}LNode,*LinkList;
void createList_tail(LinkList *L){
ElemType temp;
LNode* p,*r;
*L =(LinkList) malloc (sizeof(LNode));
(*L)->next=NULL;
(*L)->data=-1;
r=(*L);
scanf("%d",&temp);
while(temp != -1){
p=(LinkList) malloc (sizeof(LNode));
p->data = temp;
p->next=NULL;
r->next =p;
r=p;
scanf("%d",&temp);
}
}
void showList(LinkList L){
LinkList temp = L->next;
while(temp!= NULL){
printf("%d ",temp->data);
temp = temp->next;
}
}
LNode* reverseList(LinkList L){
if(L==NULL) return NULL;
LNode* head=L->next;
LNode* temp=NULL;
L->next=NULL;
//進行頭插法
while(head!=NULL){
temp=head->next;
head->next=L->next;
L->next=head;
head=temp;
}
}
void main(){
LinkList L;
createList_tail(&L);
reverseList(L);
showList(L);
}