本文主要是介绍leecode 链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
剑指 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;
}
这篇关于leecode 链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!