# [LeetCode] 链表反转相关题目

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while (q) {
ListNode *r = q->next;
q->next = p;
p = q;
q = r;
}
return p;
}
};

/**
* 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 (m == n) return head;
ListNode *cur = new ListNode(0);
ListNode *copy = cur;
for (int i = 0; i < m - 1; i++) {
cur = cur->next;
}
ListNode *temp1 = cur, *temp2 = cur->next;
cur = cur->next;
ListNode *p = cur, *q = cur->next;
for (int i = m; i < n; i++) {
ListNode *r = q->next;
q->next = p;
p = q;
q = r;
}
temp1->next = p;
temp2->next = q;
return copy->next;
}
};

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
slow = slow->next;
ListNode *p = slow;
ListNode *q = slow->next;
slow->next = NULL;
while (q) {
ListNode *r = q->next;
q->next = p;
p = q;
q = r;
}
while (p) {
if (p->val != copy->val) {
return false;
}
p = p->next;
copy = copy->next;
}
return true;
}
};

posted @ 2018-01-04 00:29 fengzw 阅读(...) 评论(...) 编辑 收藏