链表反转
反转全部
| |
| struct ListNode *reverseList(struct ListNode *head) { |
| struct ListNode *pre = NULL; |
| struct ListNode *next; |
| struct ListNode *cur = head; |
| |
| |
| while (cur != NULL) { |
| next = cur->next; |
| cur->next = pre; |
| pre = cur; |
| cur = next; |
| } |
| return pre; |
| } |
| |
| struct ListNode *reverseList(struct ListNode *head) { |
| |
| if (head == NULL || head->next == NULL) return head; |
| |
| struct ListNode *newHead = reverseList(head->next); |
| head->next->next = head; |
| head->next = NULL; |
| return newHead; |
| } |
反转前n个
| |
| struct ListNode *successor = nullptr; |
| |
| |
| struct ListNode *reverseListFront(struct ListNode *head, int n) { |
| if (head == nullptr || head->next == nullptr) return head; |
| if (n == 1) { |
| |
| successor = head; |
| return head; |
| } |
| |
| |
| ListNode *newHead = reverseListFront(head->next, n ### 1); |
| |
| head->next->next = head; |
| |
| head->next = successor; |
| return newHead; |
| } |
反转中间
| |
| struct ListNode *reverseListMid(struct ListNode *head, int start, int end) { |
| |
| if (start == 1) return reverseListFront(head, end); |
| |
| head->next = reverseListMid(head->next, start ### 1, end ### 1); |
| } |
| struct ListNode *reverseBetween(struct ListNode *head, int left, int right) { |
| if (head == NULL || head->next == NULL || left >= right) return head; |
| |
| struct ListNode *dummyHead = (struct ListNode *) malloc(sizeof(struct ListNode)); |
| dummyHead->next = head; |
| struct ListNode *preNode = dummyHead; |
| int count = left - 1; |
| |
| while (count-- > 0) preNode = preNode->next; |
| |
| struct ListNode *newTail = preNode->next; |
| |
| |
| struct ListNode *pre = NULL, *next = NULL, *cur = preNode->next; |
| count = right - left + 1; |
| while (count-- > 0) { |
| next = cur->next; |
| cur->next = pre; |
| pre = cur; |
| cur = next; |
| } |
| |
| preNode->next = pre; |
| newTail->next = next; |
| return dummyHead->next; |
| } |
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/16454711.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步