代码随想录第四天|24.两两交换链表中的节点,19. 删除链表的倒数第 N 个结点,面试题 02.07. 链表相交,142. 环形链表 II
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode newHead = new ListNode(0,head);
ListNode pre = newHead;
ListNode cur = head;
ListNode next = null;
while(cur != null && cur.next != null){
next = cur.next.next;
pre.next = cur.next;
cur.next.next = cur;
cur.next = next;
pre = cur;
cur = next;
}
return newHead.next;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)return head;
ListNode next = head.next;
ListNode newNode = swapPairs(next.next);
next.next = head;
head.next = newNode;
return next;
}
}
19. 删除链表的倒数第 N 个结点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode newHead = new ListNode(0,head);
ListNode temp = newHead;
ListNode cur = newHead;
int index = len(temp) - n - 1;
while(index -- > 0){
cur = cur.next;
}
cur.next = cur.next.next;
return newHead.next;
}
int len(ListNode node){
if(node == null)return 0;
int count = 1;
while(node.next != null){
count ++;
node = node.next;
}
return count;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode newHead = new ListNode(0,head);
ListNode fast = newHead;
ListNode low = newHead;
while(n-- > 0){
fast = fast.next;
}
while(fast.next != null){
low = low.next;
fast = fast.next;
}
low.next = low.next.next;
return newHead.next;
}
}
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode nodeA = headA;
ListNode nodeB = headB;
while(nodeA != nodeB){
nodeA = nodeA == null ? headB : nodeA.next;
nodeB = nodeB == null ? headA : nodeB.next;
}
return nodeA;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode cur = head;
ListNode pre = head;
while(cur != null &&cur.next != null ){
cur= cur.next.next;
pre = pre.next;
if(cur == pre)break;
}
if(cur == null ||cur.next == null)return null;
pre = head;
while( cur != pre){
cur = cur.next;
pre= pre.next;
}
return pre;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode index1 = fast;
ListNode index2 = head;
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}