1.求长度:
int getLen(ListNode* head){
ListNode* p = head;
int n = 0;
while(p){
p = p->next;
n++;
}
return n;
}
2.反转链表
ListNode* reverseList(ListNode* head){
ListNode* p = head;
ListNode* cur = nullptr;
while(p){
ListNode* next = p->next;
p->next = cur;
cur = p;
p = p->next;
}
return cur;
}
3.双向链表
struct DLinkedNode {
int key, value;
DLinkedNode* prev;
DLinkedNode* next;
DLinkedNode(): key(0), value(0), prev(nullptr), next(nullptr) {}
DLinkedNode(int _key, int _value): key(_key), value(_value), prev(nullptr), next(nullptr) {}
};
4.快慢指针
ListNode* sfPtr(ListNode* head){
ListNode* slow = head;
ListNode* fast = head;
while(fast){
fast = fast->next->next;
slow = slow->next;
}
return slow;
}