链表相关
24. 两两交换链表中的节点
参考文章
题目连接
思路
个人题解
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyPoint = new ListNode();
dummyPoint.next = head;
ListNode cur = dummyPoint;
ListNode temp;
ListNode first;
ListNode second;
while (cur.next != null && cur.next.next != null) {
temp = cur.next.next.next;
first = cur.next;
second = cur.next.next;
second.next = first;
first.next = temp;
cur.next = second;
cur = first;
}
return dummyPoint.next;
}
}
19.删除链表的倒数第N个节点
参考文章
题目连接
思路
个人题解
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyPoint = new ListNode();
dummyPoint.next = head;
ListNode slowPoint = dummyPoint;
ListNode fastPoint = dummyPoint;
for (int i = 0; i < n + 1; i++) {
fastPoint = fastPoint.next;
}
while (fastPoint != null) {
slowPoint = slowPoint.next;
fastPoint = fastPoint.next;
}
slowPoint.next = slowPoint.next.next;
return dummyPoint.next;
}
}
面试题 02.07. 链表相交
参考文章
题目连接
思路
个人题解
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode A = headA;
ListNode B = headB;
int aLen = 0 , bLen = 0;
while (A.next != null) {
aLen++;
A = A.next;
}
while (B.next != null) {
bLen++;
B = B.next;
}
A = headA;
B = headB;
int difLen = Math.abs(aLen - bLen);
if (aLen > bLen) {
for (int i = 0; i < difLen; i++) {
A = A.next;
}
}else {
for (int i = 0; i < difLen; i++) {
B = B.next;
}
}
while (A != null) {
if (A == B) {
return A;
}
A = A.next;
B = B.next;
}
return null;
}
}
面试题 02.07. 链表相交
参考文章
题目连接
思路
个人题解
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode fastPoint = head;
ListNode slowPoint = head;
while (fastPoint != null && fastPoint.next != null) {
slowPoint = slowPoint.next;
fastPoint = fastPoint.next.next;
if (fastPoint == slowPoint) {
fastPoint = head;
while(fastPoint != slowPoint){
fastPoint = fastPoint.next;
slowPoint = slowPoint.next;
}
return fastPoint;
}
}
return null;
}
}