数组
链表
插入
删除
双向链表
题目1:给定链表,交换每两个相邻节点并返回其头部
给定1->2->3->4,您应该将列表作为2->1->4->3
class Solution:
def reverseList(self, head):
last, cur = None, head
while cur:
next = cur.next
cur.next = last
last = cur
cur = next
return last
public ListNode reverseList(ListNode curr){
if(curr==null) return curr;
ListNode rest = curr.next;
if(rest==null) return curr;
rest = reverseList(rest);
curr.next.next = curr; // Here is the trick
curr.next =null; //
return rest;
}
题目2:给定一个链表,确定它是否有一个循环。
public boolean hasCycle(ListNode head) {
if(head == null) return false;
if(head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next.next;
while(true) {
if(slow == fast) return true;
slow = slow.next;
if(fast == null || fast.next == null || fast.next.next == null) return false;
fast = fast.next.next;
}
}
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
boolean res = false;
while (fast != null) {
fast = fast.next;
if (fast != null) {
fast = fast.next;
}
slow = slow.next;
if (fast != null && fast == slow) {
res = true;
break;
}
}
return res;
}