剑指 Offer 24. 反转链表
https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
递归写法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode * reverseList(struct ListNode* head){
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* res = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return res;
}
虚加前缀头
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* prev = NULL, *next;
while (head) {
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
特殊处理头节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode*p, *q, *h;
if (head == NULL) { //考虑为为空的情况
return NULL;
}
h = head; //考虑仅有一个的情况
for (p = head, q = p->next; q != NULL;) {
if (p == head) {
p->next = NULL;
}
h = q;
q = q->next;
h->next = p;
p = h;
}
return h;
}
24. 两两交换链表中的节点
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
递归写法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
//节点为空或仅有一个节点的时候返回
if (head == NULL || head->next == NULL) return head;
struct ListNode* next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return next;
}
迭代写法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode res, *prev = &res, *next;
prev->next = head;
while (head && head->next) {
next = head->next;
head->next = next->next;
prev->next = next;
next->next = head;
prev = head;
head = head->next;
}
return res.next;
}
25.K 个一组翻转链表
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k){
//不足k个元素终止
int n = k;
struct ListNode* curr = head, *prev, *next;
while( head && n-- ) {
head = head->next;
}
if (head == NULL) {
return curr;
}
//翻转k个元素
n = k;
prev = reverseKGroup(head, k);
while(curr && n--) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}