题目大意:给出一个链表和一个区间,将链表在区间内的节点逆转。
算法思想:
1.设置一个表头节点,方便对链表的操作。
2.找到区间内的所有节点,将其放入容器中。
3.遍历容器,将容器中的节点逆转并连接如链表中。
代码如下:
/**
* 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) {
if(head==NULL||m==n) return head;
int num=0;
ListNode *wzg=new ListNode(0);
wzg->next=head;
ListNode *pre=wzg,*p=head,*l=NULL,*r=NULL;
deque<ListNode*> Node;
while(p!=NULL){
++num;
if(num>=m&&num<=n)
Node.push_front(p);
if(num==m){
l=pre;
}
if(num==n){
r=p->next;
break;
}
pre=p;
p=p->next;
}
deque<ListNode*>::iterator pos;
for(pos=Node.begin();pos!=Node.end();++pos){
l->next=*pos;
l=l->next;
}
l->next=r;
head=wzg->next;
delete wzg;
return head;
}
};