力扣C源码
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* prev = NULL;
struct ListNode* cru = head;
while (cru) {
struct ListNode* next = cru->next;
cru->next = prev;
prev = cru;
cru = next;
}
return prev;
}
图示题解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/710f4e4dfa378db104fe5e068e65686c.jpeg)
VS运行源码
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#pragma warning(disable:4996)
using namespace std;
int n;
struct ListNode {
int val;
struct ListNode *next;
};
ListNode* List_TailInsert()
{
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
ListNode* rear = head;
printf("输入链表数据:");
int num;
for (int i = 0; i < n; i++) {
scanf("%d", &num);
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p->val = num;
rear->next = p;
rear = p;
}
rear->next = NULL;
return head;
}
ListNode* reverseList(ListNode* head) {
ListNode* head2 = head->next;
ListNode* prev = NULL;
ListNode* cru = head2;
while (cru) {
ListNode* next = cru->next;
cru->next = prev;
prev = cru;
cru = next;
}
return prev;
}
int main()
{
printf("输入要反转链表的长度:");
scanf("%d", &n);
ListNode* head = List_TailInsert();
ListNode* head3=reverseList(head);
ListNode* temp = head3;
for (int i = 0; i < n; i++) {
printf("%d ", temp->val);
temp = temp->next;
}
return 0;
}