链表
链表中每一个节点为一个对象,对象中包含两个成员变量,第一个是val,代表链表的值,第二个是next,它指向下一个节点,是下一个节点对象的引用。
定义链表
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
删除节点
给定链表中的某个节点,删除该节点
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
反转链表
普通方法:
def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
newHead = None
while head != None:
temp = head.next
head.next = newHead
newHead = head
head = temp
return newHead
使用栈解决:
一定要注意让尾巴节点next指针为空,否则将形成环:
def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return None
a = []
while head != None:
a.append(head)
head = head.next
head = a.pop()
b = head
while len(a) > 0:
n = a.pop()
b.next = n
b = n
b.next = None
return head
合并两个有序链表
合并两个升序链表,变成一个新的升序链表
递归:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if list1 is None: return list2
if list2 is None: return list1
if list1.val <= list2.val:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = self.mergeTwoLists(list1,list2.next)
return list2
判断链表是否有环
直观解法:
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
a = []
while head != None:
if head not in a:
a.append(head)
head = head.next
else:
return True
return False
快慢指针:
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
head1 = head
head2 = head
while head1 != None and head2 != None and head2.next != None:
head1 = head1.next
head2 = head2.next.next
if head1 == head2:
return True
return False