您的位置:首页 > 其它

Reverse Linked List II

2013-09-29 11:42 239 查看
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (m>n) return NULL;
if (m==n) return head;
ListNode *res=new ListNode(0);
res->next=head;
ListNode *cur=head, *pre=res, *start=NULL;
int i;
for (int i=1; i<=n; i++) {
if (i==m) {
start=pre;
}
if (i>m && i<=n) {
pre->next=cur->next;
cur->next=start->next;
start->next=cur;
cur=pre;
}
pre=cur;
cur=cur->next;

}

return res->next;
}
};


reference: http://leetcode.com/2010/04/reversing-linked-list-iteratively-and.html

The second time

/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (!head) return NULL;
if (m==n) return head;
int len=1;
ListNode *pre=new ListNode(0);
pre->next=head;
ListNode *res = pre;
while (len<m) {
pre=pre->next;
len++;
if (!pre) {
return res->next;
}
}
ListNode *cur=pre->next;
ListNode *nex=cur->next;
while (nex) {

cur->next=nex->next;
nex->next=pre->next;
pre->next=nex;
nex=cur->next;
len++;
if (len==n) {
break;
}
}
return res->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: