# 算法链表篇

### 删除排序链表的重复元素

#### 解题思路

``````class ListNode(object):
"""docstring for ListNode"""
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
"""docstring for Solution"""
if p == None or p.next == None: return head
while p.next:
if p.val == p.next.val:
p.next= p.next.next
else:
p = p.next

• 时间复杂度：O(n)
• 空间复杂度：O(1)

### 合并两个有序链表

#### 解题思路

``````class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
"""docstring for Solution"""
def merge(self, l1, l2):
if not l1: return l2
if not l2: return l1
cur = dump = ListNode(0)
while l1 and l2:
if l1.val >= l2.val:
cur.next = l2
l2 = l2.next
cur = cur.next
else:
cur.next = l1
l1 = l1.next
cur = cur.next
cur.next = l1 if l1 else l2
return dump.next

• 时间复杂度：O(n)
• 空间复杂度：O(n)

### 反转链表

#### 解题思路

``````class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
nex = None
pre = None
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
return pre

node1 = ListNode(1)
node2 = ListNode(3)
node3 = ListNode(7)
node1.next = node2
node2.next = node3

solution = Solution()
h = solution.reverseList(node1)

• 时间复杂度：O(n)
• 空间复杂度：O(1)

### 判断链表中是否有环

#### 解题思路

``````class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if fast is slow:
return True
return False

• 时间复杂度：O(n)
• 空间复杂度：O(1)

### 返回链表入环节点

#### 解题思路

``````class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
else:
return None
while fast:
if fast != slow:
if fast.next:
fast = fast.next.next
else:
return None
slow = slow.next
else:
while detection != slow:
slow = slow.next
detection = detection.next
return detection

• 时间复杂度：O(n)
• 空间复杂度：O(1)

### 判断一个链表是否为回文结构

#### 解题思路

``````class ListNode(object):
"""docstring for ListNode"""
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
"""docstring for Solution"""
fast = slow = q = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
nex = None
pre = None
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
return pre
p = reverse_List(slow.next)
while p.next:
if p.val != q.val:
return False
p = p.next
q = q.next
return p.val == q.val

• 时间复杂度：O(n)
• 空间复杂度：O(1)

### 相交链表

#### 解题思路

``````class ListNode(object):
"""docstring for ListNode"""
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
"""docstring for Solution"""