【题目】给定一个单向链表的头节点head,以及两个整数from,to;在单向链表上把第from个节点到第to个节点这一部分进行反转
【举例】
1->2->3->4->5->6->NULL;from = 2,to = 5;
反转后链表为1->5->4->3->2->6->NULL
【解题思路】先把需要反转的部分反转,然后再连接
- (1)判断边界条件;即1 <= from <= to <= N,若不满足,直接返回原来头节点
- (2)找到第from-1个节点fpre和第to+1个节点tPos
- (3)若fpre == NULL说明反转部分是包含头部节点【值得注意的部分】,则需要返回新的节点;若fpre不为NULL,则返回旧的头部节点
【C++】
ListNode* reversePart(ListNode* head,int from,int to){
int len = 0;
ListNode* cur1 = head;
ListNode* fPre = NULL;
ListNode* tPos = NULL;
while(cur1 != NULL){
len++;
fPre = (len == from -1 ? cur1 : fPre);
tPos = (len == to + 1 ? cur1 : tPos);
cur1 = cur1->next;
}
if(from > to || from < 1 || to > len){
return head;
}
cur1 = (fPre == NULL ? head : fPre->next);//判断是否为头节点
ListNode* cur2 = cur1->next;
cur1->next = tPos;
ListNode* next = NULL;
while(cur2 != tPos){
next = cur2->next;
cur2->next = cur1;
cur1 = cur2;
cur2 = next;
}
if(fPre != NULL){
fPre->next = cur1;
return head;
}
return cur1;
}
【参考】程序员代码面试指南——左程云