链表删除倒数第n个节点(双指针法)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);
ListNode* first = head;
ListNode* second = dummy;
for (int i = 0; i < n; ++i) {
first = first->next;
}
while (first) {
first = first->next;
second = second->next;
}
second->next = second->next->next;
ListNode* ans = dummy->next;
delete dummy;
return ans;
}
};
重排链表
class Solution {
public:
void reorderList(ListNode* head) {
if(head != nullptr || head->next != nullptr){
ListNode * slowIndex = head;
ListNode * fastIndex = head;
while(fastIndex->next && fastIndex->next->next){
slowIndex = slowIndex->next;
fastIndex = fastIndex->next->next;
}
ListNode * cur = slowIndex->next;
ListNode * pre = nullptr;
ListNode * tmp;
slowIndex->next = nullptr;
while(cur){
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
ListNode * link1 = head;
ListNode * link2 = pre;
ListNode * temp1;
ListNode * temp2;
while(link1 && link2){
temp1 = link1->next;
temp2 = link2->next;
link1->next = link2;
link1 = temp1;
link2->next = link1;
link2 = temp2;
}
}
}
};