赞
踩
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *pre = nullptr, *cur = head, *tmp; while(cur != NULL) { tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; } };
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverse(ListNode *pre, ListNode *cur) { if(cur == NULL) return pre; ListNode *tmp = cur->next; cur->next = pre; return reverse(cur,tmp); } ListNode* reverseList(ListNode* head) { return reverse(NULL,head); } };
在对链表的结构理解透彻后,这个问题很好解决;
写代码的时候遇到的一点小问题:在连续定义多个指针变量时,注意每个变量前都要有*号
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *start = new ListNode(), *end = start, *_dummyhead = start; start->next = head; int i = 0; while(i < n) { end = end->next; i++; } while(end->next != nullptr) { start = start->next; end = end->next; } ListNode *tmp = start->next; start->next = tmp->next; delete tmp; tmp = nullptr; return _dummyhead->next; } };
链表中,可以多个变量指向同一个结点(地址),需要注意的是,任意一个变量发生变化,都会对链表产生影响,,尤其是在修改当前节点的下一个节点指向时,一定要提前保存好本指向的那个节点,不然会彻底丢失该节点信息,再难寻觅。
这道题的主要难点在于理解相交这一概念,是指两个链表在从某一节点开始,之后的节点完全一致(结点的地址、链接顺序均完全相同),而不只是简单的数值相等。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *curA = new ListNode(), *curB = new ListNode(), *tmp = curA; int i; //获取两个链表长度 curA->next = headA; int lenA = 0; while(curA->next != NULL){ lenA ++; curA = curA->next; } curB->next = headB; int lenB = 0; while(curB->next != NULL){ lenB ++; curB = curB->next; } curA = headA; curB = headB; // 对比两个链表长度 // 不等 if(lenA > lenB) { for(i = 0; i < (lenA - lenB); i++) curA = curA->next; } else if(lenA < lenB) { for(i = 0; i < (lenB - lenA); i++) curB = curB->next; } // 后移,对比结点是否相同 for(i = 0; i < min(lenA,lenB); i++ ){ if (curA == curB) break; else{ curA = curA->next; curB = curB->next; } } return curA; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。