6-7 链表逆置 (20分)

本题要求实现一个函数,将给定单向链表逆置,即表头置为表尾,表尾置为表头。链表结点定义如下:

struct ListNode {
    int data;
    struct ListNode *next;
};

函数接口定义:

struct ListNode *reverse( struct ListNode *head );

其中head是用户传入的链表的头指针;函数reverse将链表head逆置,并返回结果链表的头指针。

裁判测试程序样例:

#include 
#include 

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 *createlist()
{
	struct ListNode *q,*head1,*tail;
	head1=tail=NULL;
	q = (struct ListNode*)malloc(sizeof(struct ListNode));
	scanf("%d", &q->data);
	while(q->data != -1)
	{
		if(head1==NULL)
		{
			head1=q;
			head1->next=NULL;
		}
		if(tail != NULL)
		{
			tail->next=q;
		}
		tail=q;
		tail->next=NULL;
		q = (struct ListNode*)malloc(sizeof(struct ListNode));
		scanf("%d",&q->data);
	}
	return head1;
}



一直错的地方在循环时最后一次没有给now->next指向,导致最后一个成为野指针;
以下为错误代码

struct ListNode *reverse( struct ListNode *head )
{
	struct ListNode *q,*head_reverse,*now;
	head_reverse=now=NULL;
	q=(struct ListNode*)malloc(sizeof(struct ListNode));
	now=q;
	while(head)
	{		
		now->next=head_reverse;
		now->data=head->data;
		head_reverse=now;
		q=(struct ListNode*)malloc(sizeof(struct ListNode));		
		now=q;
		head=head->next;
	}
	return now;
}

修改后

struct ListNode *reverse( struct ListNode *head )
{
	struct ListNode *q,*head_reverse,*now;
	head_reverse=now=NULL;
	q=(struct ListNode*)malloc(sizeof(struct ListNode));
	now=q;
	while(head)
	{		
		now->next=head_reverse;
		now->data=head->data;
		head_reverse=now;
		q=(struct ListNode*)malloc(sizeof(struct ListNode));		
		now=q;
		head=head->next;
	}
	return head_reverse;
}

但这样较繁琐


不用申请q,可以直接申请now

struct ListNode *reverse(struct ListNode *head)
{
	struct ListNode *head_reverse = NULL, *now = NULL;
	while(head)
	{
		now=(struct ListNode*)malloc(sizeof(struct ListNode));
		now->data=head->data;
		now->next=head_reverse;
		head_reverse=now;
		head=head->next;
	}
	return now;
}

你可能感兴趣的:(C语言,#,大一上学期基础算法题)