合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
public class Solution21 {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dumpy = new ListNode(-1);
ListNode res = dumpy;
while (list1 != null && list2 != null){
if(list1.val < list2.val){
dumpy.next = list1;
list1 = list1.next;
}else {
dumpy.next = list2;
list2 = list2.next;
}
dumpy = dumpy.next;
}
if(list1!= null){
dumpy.next = list1;
}
if(list2 != null){
dumpy.next = list2;
}
return res.next;
}
}
双指针
反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
迭代法
public class Solution206 {
public ListNode reverseList(ListNode head) {
if(head == null ){
return head;
}
ListNode cur = head;
ListNode pre = null;
while (cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
递归
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode last = reverseList(head.next);
// head = head.next.next;
head.next.next = head;
head.next = null;
return last;
}
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null&& fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
快慢指针
环形链表 II
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast !=null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(fast == slow){
break;
}
}
// if(fast != slow){
// return null;
// }
if(fast == null || fast.next == null){
return null;
}
slow = head;
while (slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
快慢指针,判断时 如果一个元素,不可以用fast == slow 进行判断。