leetcode hot100 链表(一)
1.相交链表
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {if(!headA||!headB) return NULL;ListNode *a=headA, *b=headB;// while循环结束后a和b应该都走了lenA+lenB的长度while(a!=b){ a=a?a->next:headB; b=b?b->next:headA; }return a;}
};
2.反转链表
经典的三指针方法。
class Solution {
public:ListNode* reverseList(ListNode* head) {ListNode* prev=nullptr;ListNode* curr=head;while(curr){ListNode* next=curr->next; //反转之前需要提前存储下一个节点curr->next=prev; //断开和下一个结点的连接,反转指针prev=curr; //前驱结点移动到当前结点curr=next; //当前结点移动到下一个结点}return prev;}
};
3.回文链表
开一个数组把链表里的值全部push_back进去,然后按判断回文数组方式判断。
class Solution {
public:bool isPalindrome(ListNode* head) {vector<int> vals;while(head){vals.push_back(head->val);head=head->next;}for(int i=0,j=vals.size()-1;i<j;i++,j--){if(vals[i]!=vals[j]) return false;}return true;}
};
4.环形链表
如果有环,则快慢指针一定会在环内相遇,类似跑步快的人会套圈跑步慢的人。
class Solution {
public:bool hasCycle(ListNode* head) {if(!head||!head->next) return false;ListNode* slow=head;ListNode* fast=head->next;while(slow!=fast) {if(!fast||!fast->next) return false;slow=slow->next;fast=fast->next->next;}return true;}
};
5.环形链表II
class Solution {
public:ListNode *detectCycle(ListNode *head) {ListNode *slow=head,*fast=head;while(fast){slow=slow->next;if(!fast->next) return nullptr;fast=fast->next->next; //快指针一次两步//快指针追上慢指针后找相遇点if (fast==slow){ListNode *ptr=head;while (ptr!=slow) {ptr=ptr->next;slow=slow->next;}return ptr;}}return nullptr;}
};
6.合并两个有序链表
归并排序思想。
class Solution {
public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {ListNode* dummy=new ListNode(0); //哨兵结点,用于维护新链表ListNode* curr=dummy; //用于构造新链表while(list1&&list2){if(list1->val<=list2->val){curr->next=list1;list1=list1->next;}else{curr->next=list2;list2=list2->next;}curr=curr->next;}if(list1) curr->next=list1;if(list2) curr->next=list2;return dummy->next; }
};
7.两数相加
class Solution {
public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* dummy=new ListNode(0);ListNode* curr=dummy;int t=0;while(l1||l2||t){int sum=(l1?l1->val:0)+(l2?l2->val:0)+t;//理论上应该是curr->next->val=sum%10,但curr->next还没创建//下面的一行代码干了两件事:创建curr->next,给curr->next->val赋值curr->next=new ListNode(sum%10); t=sum/10;curr=curr->next;if(l1) l1=l1->next;if(l2) l2=l2->next;}return dummy->next; }
};