给定一个单链表和两个位置m与n,把链表中从m到n位置的元素反转。比如说1->2->3->4->5->NULL,m = 2和n = 4,返回1->4->3->2->5->NULL。ListNode* reverseBetween(ListNode* head, int m, int n) { if (head == NULL || m == n) return head; ListNode *pHead = new ListNode(INT_MAX); pHead->next = head; ListNode *pre = pHead; int index = 1; while (pre != NULL && index < m) { pre = pre->next; index++; } if (pre == NULL) return head; ListNode *cur = pre->next; pre->next = NULL; ListNode *tail = cur; while (cur != NULL && index <= n) { ListNode *tmp = cur; cur = cur->next; tmp->next = pre->next; pre->next = tmp; index++; } tail->next = cur; return pHead->next; }
面试中常见链表问题7:反转链表2
最新推荐文章于 2021-12-04 15:38:47 发布