Tengmu 2022-02-13 08:51:34 阅读数:527
//1->2->3->4 return 2
// 1->2->3->4->5 return 3
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//l1: 1->2->3->4
//l2: 7->8->9
//result l1: 1->7->2->8->3->9->4
public void merge(ListNode l1,ListNode l2){
while(l1!=null&&l2!=null){
ListNode q1 = l1.next;
ListNode q2 = l2.next;
l1.next = l2;
l2.next = q1;
l1 = q1;
l2 = q2;
}
}
//head: 1->2->3->4->null
//return 4->3->2->1->null
public ListNode reverse(ListNode head){
ListNode prev = null;
ListNode cur = head;
while(cur!=null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
copyright:author[Tengmu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130851327905.html