面试之leetcode链表
1 数组
(1)数组的插入
如果是插入到最后,那么不用移动O(1),如果插入位置在中间为O(n).所以最好O(1),最坏O(N),平均O(N),为了插入能达到O(1),插入O(1).引入了链表
2 链表
单链表查找慢O(n),但是插入和删除O(1)
3 案例
(1)案例1 反转链表
c++版本
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head) { 4 ListNode *prev = NULL; //前指针节点 5 ListNode *curr = head; //当前指针节点 6 //每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移 7 while (curr != NULL) { 8 ListNode *nextTemp = curr->next; //临时节点,暂存当前节点的下一节点,用于后移 9 curr->next = prev; //将当前节点指向它前面的节点 10 prev = curr; //前指针后移 11 curr = nextTemp; //当前指针后移 12 } 13 return prev; 14 } 15 };
python版本
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution(object): 2 def reverseList(self, head): 3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 cur,prev=head,None 8 while cur: 9 cur.next,prev,cur=prev,cur,cur.next 10 return prev
(2)案例2 判断环
方法1:使用set存放节点的地址
方法2:快慢指针,正常情况下一个快一个慢不会相遇,所以判定条件就是是否相遇
c++版本:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 if(head==NULL) 5 { 6 return false; 7 } 8 ListNode *plow=head; 9 ListNode *pfast = head->next; 10 while(pfast!=plow) 11 { 12 if(!pfast||!pfast->next) 13 { 14 return false; 15 } 16 pfast=pfast->next->next; 17 plow=plow->next; 18 19 } 20 return true; 21 22 } 23 };
py版本
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution(object): 2 def hasCycle(self, head): 3 """ 4 :type head: ListNode 5 :rtype: bool 6 """ 7 fast=slow=head 8 while slow and fast and fast.next: 9 slow=slow.next 10 fast=fast.next.next 11 if slow is fast: 12 return True 13 return False