本題要求實現一個函數,將給定的單鏈表逆轉。
函數接口定義:
List Reverse( List L );
其中List結構定義如下:
typedef struct Node *PtrToNode;
struct Node {
ElementType Data; /* 存儲結點數據 */
PtrToNode Next; /* 指向下一個結點的指針 */
};
typedef PtrToNode List; /* 定義單鏈表類型 */
L是給定單鏈表,函數Reverse要返回被逆轉后的鏈表。
裁判測試程序樣例:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 細節在此不表 */
void Print( List L ); /* 細節在此不表 */
List Reverse( List L );
int main()
{
List L1, L2;
L1 = Read();
L2 = Reverse(L1);
Print(L1);
Print(L2);
return 0;
}
/* 你的代碼將被嵌在這里 */
輸入樣例:
5
1 3 4 5 2
輸出樣例:
1
2 5 4 3 1
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read();
void Print(List L);
List Reverse(List L);
int main()
{
List L1, L2;
L1 = Read();
L2 = Reverse(L1);
Print(L1);
Print(L2);
return 0;
}
/* 建立鏈表 */
List Read()
{
List head = NULL;
List current;
List prev = NULL;
int len = 0;
printf("pleasr enter the length of the list:\n");
scanf_s("%d", &len);
if (len == 0) return NULL;
while (len--) {
current = (List)malloc(sizeof(struct Node));
if (head == NULL)
head = current;
else
prev->Next = current;
current->Next = NULL;
scanf_s("%d", ¤t->Data);
prev = current;
}
return head;
}
/* 輸出鏈表 */
void Print(List L)
{
List p = L;
List s = L;
List temp;
if (p == NULL)
printf("NULL");
else
printf("the List is:\n");
while (p != NULL) {
printf("%d ", p->Data);
p = p->Next;
}
///* 釋放內存 */
//while(s!=NULL){
//temp=s->Next;
//free(s);
//s=temp;
//}
}
/*
鏈表反轉
思路:每次都將原第一個結點之后的那個結點放在新的表頭后面。
比如head,1,2,3,4,5
第一次:把第一個結點1后邊的結點2放到新表頭后面,變成head,2,1,3,4,5
第二次:把第一個結點1后邊的結點3放到新表頭后面,變成head,3,2,1,4,5
……
直到: 第一個結點1,后邊沒有結點為止。
*/
List Reverse(List L)
{
List head;
List temp;
List first;
if(L==NULL) return NULL;
head=(List)malloc(sizeof(struct Node));
head->Next=L; //總的頭節點,此指針節點是固定不動的
first=L;
while(first->Next!=NULL){
temp=first->Next; //保存下L后的節點
first->Next=temp->Next; //將temp節點鼓勵出來
temp->Next=head->Next; //temp節點插在head后面
head->Next=temp; //head節點接在temp上
}
return head->Next;
}
鏈表的反轉屬于基礎但是重要的題目,這塊也是卡了好久,借鑒了許多別人的博客,程序中關于內存釋放那塊存在問題。