题目描述
在链表原位置上,翻转位置m到n上的结点,指遍历链表一次
分析
如何找到第m个元素和第n个元素
如何处理前面和后面
1.保存前面部分最后一个元素
2. 保存后面部分第一个元素
3. 特殊情况都有哪些:是否需要修改头指针
C代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
if(head == NULL){
return NULL;
}
struct ListNode* mPre = NULL; //用来保存第m-1个结点地址
struct ListNode* current = head;
for(int i=1; i<m; i++){ //退出循环时候,current指向的第m个结点
mPre = current;
current = current->next;
}
struct ListNode* star = NULL;
struct ListNode* end = current;
struct ListNode* tmp = NULL;
for(int i=m; i<=n; i++){ //退出循环时候,current指向第n+1个结点
tmp = current->next;
current->next = star;
star = current;
current = tmp;
}
end->next = current; //将n+1个结点连接到翻转后的链表的末端
if(mPre == NULL){ //判断是否需要修改头指针
head = star;
}else{
mPre->next = star;
}
return head;
}
C++代码
/**
* 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)
return NULL;
ListNode* mPre = NULL;
ListNode* now = head;
for(int i=1; i<m; i++){ //退出循环时候,now指向第m个结点
mPre = now;
now = now->next;
}
ListNode* tmp = NULL;
ListNode* star = NULL;
ListNode* end = now;
for(int i=m; i<=n; i++){
tmp = now->next;
now->next = star;
star = now;
now= tmp;
}
end->next = now;
if(mPre == NULL){
head = star;
}else{
mPre->next = star;
}
return head;
}
};
ps:不要每次都还没搞清楚思路就着急着想写代码!!