24
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummyhead = new ListNode(0, head);
ListNode cur = dummyhead;
while(cur.next != null && cur.next.next != null){
ListNode next = cur.next;
ListNode nextNext = cur.next.next;
ListNode temp = cur.next.next.next;
cur.next = nextNext;
nextNext.next = next;
next.next = temp;
//cur = next;
cur = cur.next.next;
}
return dummyhead.next;
}
}
19:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null) return head;
ListNode dummy = new ListNode(0, head);
ListNode fast = dummy;
ListNode slow = dummy;
for(int i = 0; i <= n; i++){
fast = fast.next;
}
while(fast != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
面试题 02.07:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode getA = headA;
int countA = 0;
ListNode getB = headB;
int countB = 0;
while(getA != null){
getA = getA.next;
countA++;
}
while(getB != null){
getB = getB.next;
countB++;
}
getA = headA;
getB = headB;
if(countA < countB){
ListNode temp = headA;
getA = headB;
getB = headA;
int temp1 = countA;
countA = countB;
countB = temp1;
}
int gap = countA - countB;
for(int i = 0; i < gap; i++){
getA = getA.next;
}
while(getA != null && getB != null){
if(getA == getB){
return getA;
}
getA = getA.next;
getB = getB.next;
}
return null;
}
}
142:
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast){
ListNode start = head;
ListNode cycle = fast;
while(start != cycle){
start = start.next;
cycle = cycle.next;
}
return cycle;
}
}
return null;
}
做下来感觉链表主要是思路和细节