牛客网-BM2 链表内指定区间反转
用到了BM1的思路。
#include <stdio.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) { if (head == NULL) return NULL; if (m == n) return head; struct ListNode* start = head; struct ListNode* startPre; struct ListNode* p = head; // 先到m的位置 int pos = 1; while(pos < m) { startPre = p; p = p->next; start = p; pos++; } struct ListNode* end = start; p = end->next; //printf("sss %d %d\n", start->val, p->val); // 把p放在最前面,实现倒序 // 1.end的next指向p的next // 2.把head放到p之后 while(pos < n) { end->next = p->next; p->next = start; start = p; p = end->next; pos++; } // 追加逆序数据 if (m != 1) { startPre->next = start; } else { head = start; } return head; } void printListNode(struct ListNode* pHead) { struct ListNode *p = pHead; while(p != NULL) { printf("%d ", p->val); p = p->next; } printf("\n"); } int main() { ListNode pHead; pHead.val = 3; ListNode node2; node2.val = 5; node2.next = NULL; pHead.next = &node2; printListNode(&pHead); struct ListNode *head = reverseBetween(&pHead, 1, 2); printListNode(head); return 0; }