概述
死记硬背迭代
迭代
image.png
图抄的leetcode上面题解
用一个prev 和 cur,让链表反着指向,然后再让prev和cur都往前一步走,继续操作
但是当你拆掉 24 指向 12的链子的时候,和后面的联系就断了,所以需要一个temp变量去保存下一个的值
然后再帮助prev和curr往前走
附上代码
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// #include <uthash.h>
struct ListNode {
int val;
struct ListNode *next;
};
typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head){
ListNode *curr = head;
ListNode *prev = NULL;
while (curr) {
ListNode *tempNext = curr->next;
curr->next = prev;
prev = curr;
curr = tempNext;
}
return prev;
}
int main()
{
ListNode arr[3];
arr[0].val = 1;
arr[1].val = 2;
arr[2].val = 3;
arr[0].next = &arr[1];
arr[1].next = &arr[2];
arr[2].next = NULL;
for (int i = 0; i < 3; i++) {
printf ("%d ", arr[i].val);
}
printf("\n");
ListNode *res = reverseList(&arr[0]);
printf("%d", res->val);
}