234. 回文链表 简单
def isPalindrome(self, head: ListNode) -> bool:
if head==None:
return True
#确定前半部分的开头slow
slow,fast=head,head
while fast.next!=None and fast.next.next!=None:
slow=slow.next
fast = fast.next.next
# 将后半部分倒转,此时pre指向后半部分第一个节点
p = slow.next
pre = None
while p:
nxt = p.next
p.next = pre
pre = p
p = nxt
res = True
first,second = head,pre
while res and second!=None :
if first.val==second.val:
first,second=first.next,second.next
else:
res = False
return res
21. 合并两个有序链表 简单
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// 类似归并排序中的合并过程
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
cur = cur.next;
l1 = l1.next;
} else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
// 任一为空,直接连接另一条链表
if (l1 == null) {
cur.next = l2;
} else {
cur.next = l1;
}
return dummyHead.next;
}
141. 环形链表 简单
快慢指针
def hasCycle(self, head: ListNode) -> bool:
if head==None or head.next==None:
return False
slow = head
fast = head.next
while slow!=fast:
# 快指针会率先到达末位
if fast==None or fast.next==None:
return False
slow = slow.next
fast = fast.next.next
return True
160. 相交链表 简单
双指针,两人走的长度一致,步调一致,短的先进入到下一段,如果有相交,最后一部分肯定是一样的
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
p = headA
q = headB
while p!=q: # 若是有缘,你们早晚会相遇
p=headB if p==None else p.next # 当你走到终点时,开始走她走过的路
q=headA if q==None else q.next # 当她走到终点时,开始走你走过的路
return p