题目: 链表逆置
解析
链表:
初始
front = head;
front_next = front->next;
循环
第一轮循环
front->next = new_head;
new_head = front;
front = front_next;
front_next = front->next;
第二轮循环
front->next = new_head;
new_head = front;
front = front_next;
front_next = front->next;
第三次循环
第四次循环
第五次循环
第六次循环
第六次循环的初始状态
front->next = new_head;
new_head = front;
front = front_next;
if(front==NULL) break;
判断条件满足,退出循环。
返回new_head
代码
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *reverse( struct ListNode *head ){
if(!head) return NULL;
struct ListNode *new_head = NULL;
struct ListNode *front,*front_next;
front = head;
front_next = front->next;
while(1){
front->next = new_head;
new_head = front;
front = front_next;
if(front==NULL) break;
front_next = front->next;
}
return new_head;
}
//创建链表
struct ListNode *createlist(){
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->data = 1;
struct ListNode *point1 = (struct ListNode *)malloc(sizeof(struct ListNode));
point1->data = 2;
head->next = point1;
struct ListNode *point2 = (struct ListNode *)malloc(sizeof(struct ListNode));
point2->data = 3;
point1->next = point2;
struct ListNode *point3 = (struct ListNode *)malloc(sizeof(struct ListNode));
point3->data = 4;
point2->next = point3;
struct ListNode *point4 = (struct ListNode *)malloc(sizeof(struct ListNode));
point4->data = 5;
point3->next = point4;
struct ListNode *point5 = (struct ListNode *)malloc(sizeof(struct ListNode));
point5->data = 6;
point4->next = point5;
struct ListNode *point6 = (struct ListNode *)malloc(sizeof(struct ListNode));
point6->data = -1;
point5->next = point6;
point6->next = NULL;
return 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;
}