Linked list notes
如何判断while循环里面的条件。一般来说是结束的时候,如果不清楚则看while里面,需要用到next的ListNode不为空。
如果node在后面的操作中会丢失,那么先要cache。比如reverse里面的,cur.next会丢失。
1. Reverse
其实reserse就只有有个操作,cur.next = prev,其它的就是调整pre 和cur。
2. Merge
3. Find mid and cut
如果node在后面的操作中会丢失,那么先要cache。比如reverse里面的,cur.next会丢失。
1. Reverse
其实reserse就只有有个操作,cur.next = prev,其它的就是调整pre 和cur。
ListNode prev = null;
ListNode cur = mid;
while(cur != null) {
ListNode temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
2. Merge
while (l1 != null) {
ListNode n1 = l1.next, n2 = l2.next;
l1.next = l2;
if (n1 == null)
break;
l2.next = n1;
l1 = n1;
l2 = n2;
}
3. Find mid and cut
ListNode slow = head;
ListNode fast = head;
ListNode prev = null;
while(fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next =null;
return slow;
4. Determine cycle
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
5. Merge two sorted list
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode res = new ListNode(0);
dummy = res;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
res.next = l1;
l1 = l1.next;
} else {
res.next = l2;
l2 = l2.next;
}
res = res.next;
}
while (l1 !=null) {
res.next = l1;
}
if(l2 != null) {
res.next = l2;;
}
return dummy.next;
}
}
评论
发表评论