ReverseList I, II
问题描述,给定一个list,起点m,终点n。试只遍历一次链表达到将m->n之间反转的目的。对于I来m=第一个节点,n=最后一个节点。我们可以假设0<=m<=n<=length of the list. 分析:因为我们只能遍历一次列表,所以我们考虑在遍历列表的时候计数,计算当前是第几个节点。假设当前是第i个节点。如果i<m我们不操作。如果i>n我们也不操作。如果i在m和n之间呢?
首先我们记录第m个节点前的节点,记为LL。 然后将第M个节点记为first 然后对于m到n之间的点,我们将其由A->B ==>B->A. 当我们遍历到第n个节点的时候,标记为last 将第n个节点的next标记为RR. 至此我们就获得了反转了区间m~n,并且获得了区间前后的元素LL和RR 然后我们另LL->next = last first->next = RR即可 如下图所示 代码
ListNode* reverseBetween ( ListNode* head, int m, int n) {
if ( head == NULL || head-> next == NULL )
return head;
if ( m == n)
return head;
ListNode* dump = new ListNode ( 0 ) ;
dump-> next = head;
ListNode* last = dump;
ListNode* cur = head;
m - = 1 ;
n - = 1 ;
ListNode* ll;
ListNode* lr;
ListNode* rl;
ListNode* rr;
int idx = 0 ;
while ( cur) {
if ( idx > n)
break ;
if ( idx == m) {
ll = last;
lr = cur;
}
if ( idx == n) {
rl = cur;
rr = cur-> next;
}
if ( idx > m && idx <= n) {
ListNode* newCur = cur-> next;
cur-> next = last;
last = cur;
cur = newCur;
} else {
last = cur;
cur = cur-> next;
}
idx + = 1 ;
}
ll-> next = rl;
lr-> next = rr;
return dump-> next;
}