用虚拟头节点来做,画图理清思路
注意要new 虚拟头节点,listnode dummy = new listnode(-1)
递归法还没看
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
ListNode temp;
ListNode frist;
ListNode second;
while(cur.next != null && cur.next.next != null){
second = cur.next.next;
frist = cur.next;
temp = cur.next.next.next;
cur.next = second;
second.next = frist;
frist.next = temp;
cur = frist;
}
return dummy.next;
}
}
快慢指针,fast先走n+1,注意既然虚拟了头节点,最后返回的肯定是dummy.next
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fast;
ListNode slow;
fast = dummy;
slow = dummy;
// while((n+1)--){
// fast = fast.next;
// }
for(int i=1;i<=n+1;i++){
fast = fast.next;
}
while(fast != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
思路是两个连表既然从某处开始就是相交的,那么说从从某处开始后面的东西都是一致的,即最后几项都是一致的,所以较长的链表的前面几项没用,直接将较长链表的指针移动到余下的长度与较短的链表的长度相等的地方,然后分情况讨论逐个比较即可
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode cur1 = headA;
ListNode cur2 = headB;
int count1 = 0;
int count2 = 0;
while(cur1 != null){
cur1 = cur1.next;
count1++;
}
while(cur2 != null){
cur2 = cur2.next;
count2++;
}
cur1 = headA;
cur2 = headB;
if(count1>count2){
for(int i = 1;i <=count1-count2;i++){
cur1 = cur1.next;
}
for(int j = 1;j<=count2;j++){
if(cur1 == cur2){
return cur1;
}
cur1 = cur1.next;
cur2 = cur2.next;
}
}
if(count1<=count2){
for(int i = 1;i <=count2-count1;i++){
cur2 = cur2.next;
}
for(int j = 1;j<=count1;j++){
if(cur1 == cur2){
return cur1;
}
cur1 = cur1.next;
cur2 = cur2.next;
}
}
return null;
}
}
挺难的,考研数学思维,二刷也认真看
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode index1 = head;
ListNode index2 = slow;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}