链表反转 https://leetcode-cn.com/problems/reverse-linked-list/
public ListNode reverseList(ListNode head) {
if(head ==null || head.next ==null){
return head;
}
ListNode next, cur, pre;
pre = head;
cur = head.next;
head.next = null;
while(cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
链表是否有环 https://leetcode-cn.com/problems/linked-list-cycle/ 这个也是经典题目,解法比较巧妙。
public boolean hasCycle(ListNode head) {
if(head==null)
return false;
ListNode fast = head, slow = head;
while(true) {
if(fast.next == null || fast.next.next == null)
return false;
fast = fast.next.next;
slow = slow.next;
if(fast == slow) {
return true;
}
}
}
|