0%

代码随想录第八天

链表-反转链表

题目链接

采用双指针方法,并且设置一个临时值保存cur->next的值

1
2
3
4
5
6
7
8
9
10
11
12
13
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* cur = head;
struct ListNode* temp;
struct ListNode* pre = NULL;
while(cur){
temp = cur->next;
cur->next = pre;

pre = cur;
cur = temp;
}
return pre;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct ListNode* reverse(struct ListNode* pre, struct ListNode* cur){
if(cur == NULL) return pre;
struct ListNode* tmp = cur->next;
cur->next = pre;
//下面的步骤也和双指针一个逻辑
// pre = cur;
//cur = tmp
return reverse(cur, tmp);
}
struct ListNode* reverseList(struct ListNode* head){
//这里其实和双指针初始化的时候一样
// pre = NULL
// cur = head;
return reverse(NULL, head);
}