- 两两交换链表中的节点
链表的指针,要仔细画图,搞清楚cur和cur的next在哪里
这个题还是有点绕的,两两一组交换,还有奇偶数要考虑
class Solution {
public:ListNode* swapPairs(ListNode* head) {ListNode* dummyhead = new ListNode(0);dummyhead -> next = head;ListNode* cur = dummyhead;while(cur -> next != NULL && cur -> next -> next != NULL) {ListNode* tmp = cur -> next;ListNode* tmp1 = cur -> next -> next -> next;cur -> next = cur -> next -> next;cur -> next -> next = tmp;tmp -> next = tmp1;cur = cur -> next -> next;}return dummyhead -> next;}
};
19.删除链表的倒数第N个节点
这个题又用到了快慢指针,快指针先走N+1步,然后快慢一起走到NULL,刚好慢指针就是倒数第N+1个
删除操作的时候,cur要放到被删除的前一个
class Solution {
public:ListNode* removeNthFromEnd(ListNode* head, int n) {ListNode* dummyhead = new ListNode(0);ListNode* fast = dummyhead;ListNode* slow = dummyhead;dummyhead -> next = head;while(n-- && fast != NULL) {fast = fast -> next;}fast = fast -> next;while(fast != NULL) {fast = fast -> next;slow = slow -> next;}slow -> next = slow -> next -> next;return dummyhead -> next;}
};
160 链表相交
这个题题意不好理解,
如果已经是相交的链表,结尾对齐以后,如果有完全一样的节点,后面的节点都是同一个next,一定是相交的
判断节点的时候是节点本身相等,不是值相等
距离之和一样的思路也很巧妙,在两趟以内一定会相交
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {//注意审题,题目给出的链表如果是相交的,那就已经相交了,不用你再制造成相交//路径a+b+c相等,是巧妙的方法//用直观方法推理,只要结尾长度相等了,有了相等的节点,那就说明从这个完全相同的节点以后,剩下的都相等了,从这个完全相同的节点以后,剩下的节点只有一个next//题目的终极目的,本身就是为了找到两个完全相同的节点,而且是最前面出现的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;}
};
142.环形链表II
这个题看着解析基本理解了
数学的方法是技巧很强的
环形链表也用到了快慢指针
思路不好想,不熟练
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;}
};
链表到此结束了,以后还要多练,现在感觉比以前自己做题还是有所提升的,做题思路,做题方法都有了规范