在这里插入代码片class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *A =headA;
ListNode *B =headB;
int lengthA=0;
while(headA!=NULL){
lengthA++;
headA = headA->next;
}
int lengthB=0;
while(headB!=NULL){
lengthB++;
headB = headB->next;
}
while(lengthB>lengthA){
lengthA++;
B = B->next;
}
while(lengthB<lengthA){
lengthB++;
A = A->next;
}
while(A!=B){
A = A->next;
B = B->next;
if(A==NULL){
return NULL;
}
}
return A;
}
};
找到链表倒数N个结点
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode* pre = head;
ListNode* post = head;
int count = 0;
while(count<k){
post = post->next;
count++;
}
while(post!=NULL){
post = post->next;
pre = pre ->next;
}
return pre;
}
};
反转链表,头插法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* current = head;
ListNode* pre = NULL;
while(current){
ListNode* post = current->next;
current->next = pre;
pre = current;
current = post;
}
return pre;
}
};