Reverse Linked List II

来源:互联网 发布:native.js下载 编辑:程序博客网 时间:2024/06/11 04:54

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

解析:因为要求对于链表 一趟就将 m和n之间的数字逆转。在这里我们想到了将[m,n]之间的链表进行逆转再与两端进行连接。

即使这样的

1->2->3->4->5->6->7 参数m=2,n=4

那么  1-> ( 4->3->2  ) ->5->6->7

#include <iostream>using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *reverseBetween(ListNode *head, int m, int n) {if( m == n)return head;if((n - m) <= 2){ListNode *first;ListNode *last;ListNode *p = head;int index = 1;while(p!=NULL){if( m==index){first = p;}if( n==index){last = p;break;}index++;p = p->next;}int temp = first->val;first->val = last->val;last->val = temp;}else{ListNode *firstBefore=head;ListNode *last;ListNode *p;ListNode *q;ListNode *r;ListNode *iter = head;int index = 1;<strong><span style="color:#FF6666;">if( m == 1)firstBefore = NULL;</span></strong>while(iter!=NULL){if( m > 1 && index < m){firstBefore = iter;}if( m == index){p = iter;q = p->next;r = q->next;}if(index == n){last = iter;p->next = iter->next;q->next = p;p = q;q = r;r = r->next;while(r != iter){q->next = p;p = q;q = r;r = r->next;}q->next = p;r->next = q;break;}iter = iter->next;index++;}<strong><span style="color:#FF6666;">if(firstBefore == NULL)head = last;</span></strong>else{firstBefore ->next = last;}}return head;}void printLinkedList(ListNode *head){while(head != NULL){cout << head->val << " ";head = head->next;}cout << endl;}int main(void){ListNode *head;ListNode *p;ListNode *temp = (ListNode *)malloc(sizeof(ListNode));temp->val = 1;head = temp;p=head;for(int i=2;i<=7;i++){temp = (ListNode *)malloc(sizeof(ListNode));temp->val = i;p->next = temp;p = temp;}p->next = NULL;printLinkedList(head);head = reverseBetween(head, 1, 7);printLinkedList(head);system("pause");return 0;}


0 0
原创粉丝点击