6-3 链表逆置 (20 分) 本题要求实现一个函数,将给定单向链表逆置,即表头置为表尾,表尾置为表头。链表结点定义如下:
·
```c
#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;
}
struct ListNode* createlist(void) /*裁判实现,细节不表*/
{
struct ListNode* head = NULL, * tail = NULL, * p = NULL;
int data;
while (1) {
scanf("%d", &data);
if (data == -1)
return head;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->data = data;
p->next = NULL;
if (head) {
tail->next = p;
tail = p;
}
else {
head = p;
tail = p;
}
}
}
/* 你的代码将被嵌在这里 */
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* p = head;
struct ListNode* newhead = NULL;
while (p)
{
struct ListNode* abc = (struct ListNode*)malloc(sizeof(struct ListNode));
abc->data = p->data; abc->next=NULL;
if (newhead == NULL)
newhead = abc;
else
{
abc->next = newhead;
newhead = abc;
}
p = p->next;
}
return newhead;
}
更多推荐
所有评论(0)