24. 两两交换链表中的节点
题目链接:两两交换链表中的节点
轻松拿下,没什么疑点,注意一下头节点的位置就行。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode fakehead = new ListNode(-1);
fakehead.next = head;
ListNode temp;
ListNode left=fakehead;
ListNode right=head;
while(left.next!=null&&left.next.next!=null){
temp = left.next.next.next;
left.next=right.next;
right.next=temp;
left.next.next=right;
left=right;
right=left.next;
}
return fakehead.next;
}
}
19.删除链表的倒数第N个节点
题目链接:两两交换链表中的节点
这个刚开始根本想不到用两个结点。只能说多练多练多练!
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode res = new ListNode(0);
res.next = head;
ListNode fastIndex = res;
ListNode slowIndex = res;
for (int i = 0; i <= n; i++) {
fastIndex = fastIndex.next;
}
while (fastIndex != null) {
fastIndex = fastIndex.next;
slowIndex = slowIndex.next;
}
//重点:
if (slowIndex.next != null) {
slowIndex.next = slowIndex.next.next;
}
return res.next;
}
}
142.环形链表II
题目链接:两两交换链表中的节点
和上一题一样。过几天抹掉答案重新做一次。
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;
}
}