标签:style blog http color io os ar for sp
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 ≤ m ≤ n ≤ length of list.
思路一:为方便对m=1的处理,对链表创建头结点tmphead,对应于上面例子,lt->val=1;lt_next->val=2;rt->val=4;rt_next->val=5;
然后对(lt_next,rt)之间的链表翻转(lt_next->next=rt_next);
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode tmphead(-1); tmphead.next=head; ListNode *cur=head; ListNode *lt,*lt_next,*rt,*rt_next; int count=1; if(m==n) return head; while(cur) { if(m==1) { lt=&tmphead; lt_next=head; } else if(count==m-1) { lt=cur; lt_next=cur->next; } if(count==n) { rt=cur; rt_next=cur->next; } ++count; cur=cur->next; } rt->next=NULL; while(lt_next) { ListNode *tmp=lt_next->next; lt_next->next=rt_next; rt_next=lt_next; lt_next=tmp; } lt->next=rt_next; return tmphead.next; } };
思路二:简化思路一,不必记录n所对应的节点,通过循环直接逆转链表;
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode *lt=NULL; ListNode *lt_next=head; for(int i=0;i<m-1;++i) { lt=lt_next; lt_next=lt_next->next; } ListNode *link; ListNode *link_next=lt_next->next; ListNode *lt_nextsave=lt_next; for(int i=m+1;i<=n;++i) { link=link_next; link_next=link_next->next; link->next=lt_next; lt_next=link; } lt_nextsave->next=link_next; if(lt) lt->next=lt_next; else return lt_next; return head; } };
标签:style blog http color io os ar for sp
原文地址:http://www.cnblogs.com/chengyuz/p/4048039.html