6-5 連結串列逆置(20 分)——頭插或者重開新連結串列頭插
阿新 • • 發佈:2019-02-11
6-5 連結串列逆置(20 分)
本題要求實現一個函式,將給定單向連結串列逆置,即表頭置為表尾,表尾置為表頭。連結串列結點定義如下:
struct ListNode {
int data;
struct ListNode *next;
};
函式介面定義:
struct ListNode *reverse( struct ListNode *head );
其中head是使用者傳入的連結串列的頭指標;函式reverse將連結串列head逆置,並返回結果連結串列的頭指標。
裁判測試程式樣例:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist(); /*裁判實現,細節不表*/
struct ListNode *reverse( struct ListNode *head );
void printlist( struct ListNode *head )
{
struct ListNode *p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf ("\n");
}
int main()
{
struct ListNode *head;
head = createlist();
head = reverse(head);
printlist(head);
return 0;
}
/* 你的程式碼將被嵌在這裡 */
輸入樣例:
1 2 3 4 5 6 -1
輸出樣例:
6 5 4 3 2 1
struct ListNode *reverse(struct ListNode *head)
{
struct ListNode *newhead=NULL, *tail=NULL ,*p=head;
while (p)
{
tail = p->next;//記錄後驅
p->next = newhead; //插到前面
newhead = p;//更新
p = tail;//下一個
}
return newhead;
}
struct ListNode *reverse(struct ListNode *head)
{
struct ListNode *newhead=NULL, *now=NULL;
while (head)
{
now = (struct ListNode*)malloc(sizeof(struct ListNode));
now->data = head->data;
now->next = newhead;
newhead=now;
head = head->next;
}
return now;
}
這裡寫程式碼片