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;
}
/* 你的代码将被嵌在这里 */
代码修改如下,供参考:
#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 *reverse( struct ListNode *head )
{
if(head==NULL) return head;
struct ListNode *p,*q;
p = head; //p = head->next;
head = NULL; //head->next==NULL;
while(p!=NULL)
{
q = p;
p = p->next;
q->next=head;//q->next=head->next;
head = q; //head->next=q;
}
return head;
}
代码麻烦代码块
你自己对比吧
```c
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#define N 10
typedef struct Node
{
int data;
struct Node* next;
}Node_t;
Node_t* AollcNode(int x)
{
Node_t* new = (Node_t*)malloc(sizeof(Node_t));//新建一个节点
//初始化
new->data = x;
new->next = NULL;
return new;
}
//头插入
void InsertNode(Node_t* head, int i)
{
Node_t* p = AollcNode(i);
p->next = head->next;
head->next = p;
}
//打印
void ShowNode(Node_t* head)
{
Node_t* p = head->next;
while (p)
{
printf("%d->", p->data);
p = p->next;
}
printf("NULL\n");
}
//尾插入
void EndInsertNode(Node_t* head, Node_t** end, int i)
{
Node_t* n = AollcNode(i);
(*end)->next = n;
*end = n;
}
Node_t* ReverseList(Node_t* head)
{
Node_t* p = head->next;//指向第一个节点
Node_t* t = p->next;//指向第第二个节点
Node_t* p1 = p;
p1->next = NULL;
while (t)
{
p = t;
t = t->next;
p->next = head->next;
head->next = p;
}
}
int main()
{
Node_t* head = AollcNode(0);//首先要有一个头节点
Node_t* end = head;//专门记录最后一个节点的位置
printf("头插入...\n");
for (int i = 1; i < N; i++)//插入节点的个数(传入数据)
{
InsertNode(head, i);//头插入
ShowNode(head);//展示链表
//Sleep(1000);
}
printf("逆序...\n");
Node_t* p1 = ReverseList(head);
ShowNode(p1);
printf("尾插入...\n");
for (int i = 1; i < N; i++)//节点个数
{
//尾插法,要找到上一个节点,插入新的节点
//所以每增加一个新节点,尾指针都需要指针它,并且还要保存
//所以需要传址调用
EndInsertNode(head, &end, i);
ShowNode(head);
//Sleep(1000);
}
printf("逆序...\n");
Node_t* p = ReverseList(head);
ShowNode(p);
free(head);
head = NULL;
return 0;
}
```