24.两两交换链表中的节点
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummyNode = new ListNode();
dummyNode.next = head;
ListNode cur = dummyNode;
while (cur.next != null && cur.next.next != null) {
ListNode p = cur.next;
ListNode q = cur.next.next;
ListNode r = q.next;
cur.next = q;
q.next = p;
p.next = r;
cur = p;
}
return dummyNode.next;
}
}
19.删除链表的倒数第N个节点
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head.next == null) {
return null;
}
ListNode dummyNode = new ListNode();
dummyNode.next = head;
ListNode p = dummyNode;
ListNode q = dummyNode;
for (int i = 0; i < n; i++) {
p = p.next;
}
while (p.next != null) {
p = p.next;
q = q.next;
}
q.next = q.next.next;
return dummyNode.next;
}
}
面试题 02.07. 链表相交
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode p = headA;
ListNode q = headB;
int flag = 0;
while (p.next != null || q.next != null) {
if (p == q) {
break;
}
if (p.next == null) {
if (flag == 2) {
break;
}
flag++;
}
if (q.next == null) {
if (flag == 2) {
break;
}
flag++;
}
p = p.next != null ? p.next : headB;
q = q.next != null ? q.next : headA;
}
return p == q ? p : null;
}
}
142.环形链表II
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
if (head.next == head) {
return head;
}
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode slow = head;
ListNode fast = head;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
int cnt = 0;
if (fast == null || fast.next == null) {
return null;
}
ListNode cur = head;
while (cur != slow) {
cur = cur.next;
slow = slow.next;
}
return slow;
}
}