1 单链表知识整理
1)数组回顾
数组:是相同数据类型的元素按一定顺序排列的集合。数组在内存中连续,会自动生成连续的下标。
2)链表
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
3)数组与链表区别
A 数组静态分配内存,链表动态分配内存
B 数组内存中连续,链表不连续
C 数组元素在栈区,链表元素在堆区
D 数组利用下标定位,时间复杂度为O(1),链表定位元素时间复杂度O(n);
E 数组插入或删除元素的时间复杂度O(n),链表的时间复杂度O(1)。
2 leetcode # 142 Linked List Cycle II
题目如图:
way1: solution demo
思路:先判断ListNode:head是否有环,然后找到环开始的位置
步骤:1)设置两个ListNode:fast快指针和slow慢指针,fast步长为2,slow步长为1,若head有环,fast和slow早晚会相遇;
2)若fast==slow,则表示ListNode有环,进行3),否则return None);
3)ListNode有环,设置新指针p,当p与slow相遇时,return slow;
(参考见:链接1)
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast,slow,p= head,head,head
while (fast!=None)&(slow!=None):
fast = fast.next
slow = slow.next
if fast!=None:
fast = fast.next
if (slow!=None)&(slow==fast):
while p!=slow:
p = p.next
slow = slow.next
return p
return None
result:
way 2:solution demo
思路:利用指针域的唯一性:ListNode若有环,指针将指向之前曾出现的位置,因此可以找到环的结点;若无环指针最终会指向None。
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
list = []
while head!=None:
list.append(head)
head = head.next
if head in list:
return head
return None
(唉,改了几遍都与这个(链接2)相差甚远。。。结果就不附上了)
3 leetcode # 206 Reverse Linked List
问题:
solution demo:
思路:首先判断ListNode是否为空,若是直接返回;若否,单链表反转,最直接思路为调换头尾顺序,具体见步骤
步骤:1)判断ListNode是否为空,空则返回ListNode,否则到下一步2);
2)设置newhead=head,将newhead.next = None,即newhead仅存放head中的第一个元素;
3)设置中间单链表tempNode=head.next,将tempNode.next=newhead,替换元素后,tempNode存放head中[第2个元素,第1个元素],并将newhead=tempNode,以此循环至head.next指为None,返回newhead;
参考博客链接:链接3
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head!=None:
newhead = head
next_ = newhead.next
newhead.next = None
while next_!=None:
tempNode = next_
next_ = next_.next
tempNode.next = newhead
newhead = tempNode
return newhead
else:
return head
result(python2和python3得到的runtime不一样)
参考:
链接1:https://leetcode.com/problems/linked-list-cycle-ii/discuss/226123/java-0ms-beats-100
链接2:https://leetcode.com/problems/linked-list-cycle-ii/discuss/221872/Easy-Python-7-line-solution%3A