24. Swap Nodes in Pairs
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = pre->next;
while(cur != NULL && cur->next != NULL){
ListNode* post = cur->next;
ListNode* tmp = post->next;
pre->next = post;
post->next = cur;
cur->next = tmp;
pre = cur;
cur = tmp;
}
return dummy->next;
}
};
注意:
1.return dummy->next而不是head;
2.最好把post放到循环里面,不然可能会出界
19. Remove Nth Node From End of List
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* fast = dummy;
for(int i=0; i<n; i++){
fast = fast->next;
}
ListNode* slow = dummy;
while(fast->next != NULL){
slow = slow->next;
fast = fast->next;
}
ListNode* nextNode = slow->next->next;
ListNode* tmp = slow->next;
slow->next = nextNode;
delete tmp;
return dummy->next;
}
};
160. Intersection of Two Linked Lists
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while(curA != NULL){
curA = curA->next;
lenA++;
}
while(curB != NULL){
curB = curB->next;
lenB++;
}
curA = headA;
curB = headB;
if(lenA < lenB){
swap(lenA, lenB);
swap(curA, curB);
}
int dif = lenA-lenB;
while(dif--){
curA = curA->next;
}
while(curB!= NULL){
if(curA == curB)
return curA;
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
while(curA != curB){
if(curA == NULL){
curA = headB;
}else{
curA = curA->next;
}
if(curB == NULL){
curB = headA;
}else{
curB = curB->next;
}
}
return curA;
}
};
节点一样和值一样是不同的,直接用curA == curB判断就可以
142. Linked List Cycle II
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
if(fast == NULL || fast->next == NULL)
return NULL;
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
记得判断没有环时候的情况
141. Linked List Cycle
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
};
21. Merge Two Sorted Lists
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* cur1 = list1;
ListNode* cur2 = list2;
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
while(cur1 != NULL && cur2 != NULL){
if(cur1->val <= cur2->val){
cur->next = cur1;
cur1 = cur1->next;
}else if(cur1->val > cur2->val){
cur->next = cur2;
cur2 = cur2->next;
}
cur = cur->next;
}
if(cur1) cur->next = cur1;
if(cur2) cur->next = cur2;
return dummy->next;
}
};