Java
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode next = head.next;
ListNode newNode = swapPairs(next.next);
next.next = head;
head.next = newNode;
return next;
}
}
C++
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0,head);
ListNode* cur = dummy;
while(cur->next != nullptr && cur->next->next != nullptr){
ListNode* next = cur->next->next->next;
ListNode* tmp = cur->next;
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = next;
cur = cur->next->next;
}
return dummy->next;
}
};
Java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(0,head);
ListNode start = pre ,end = pre;
while(n!=0){
start = start.next;
n--;
}
while(start.next!=null){
start = start.next;
end = end.next;
}
end.next = end.next.next;
return pre.next;
}
}
C++
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0,head);
ListNode* fast = dummy;
ListNode* slow = dummy;
while(n-- && fast != nullptr){
fast = fast->next;
}
while(fast->next != nullptr){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
Java
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA;
ListNode B = headB;
while(A!=B){
A = A == null ? headB : A.next;
B = B == null ? headA : B.next;
}
return A;
}
}
C++
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* A = headA;
ListNode* B = headB;
while(A!=B){
A = A==NULL ? headB : A->next;
B = B==NULL ? headA : B->next;
}
return A;
}
};
Java
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
ListNode index1 = fast;
ListNode index2 = head;
while(index1!=index2){
index1=index1.next;
index2=index2.next;
}
return index1;
}
}
return null;
}
}
C++
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast==slow){
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1!=index2){
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return NULL;
}
};