搞两个临时结点存储即将丢失的结点的值,再进行处理。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyhead = new ListNode();
dummyhead.next = head;
ListNode cur = dummyhead;
while(cur.next != null && cur.next.next != null){ //注意cur.next要写前面,不然可能空指针
ListNode temp1 = cur.next; //临时存结点1
ListNode temp2 = cur.next.next.next; //临时存结点3
cur.next = cur.next.next; //虚拟头结点指向2
cur.next.next = temp1; //2指向1
cur.next.next.next = temp2; //1指向3
cur = cur.next.next; //指针后移两位进行下次交换
}
return dummyhead.next;
}
}
但是我还有个疑惑,为什么dummyhead.next是头结点,头结点不是已经换到2去了吗?
先计算共有多少个结点,然后再正向循环到要删除结点的前一个结点进行操作。
但是好像只能把cur循环到最后一个,怎么找到要删除结点的前一个结点呢?看看讲解。。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyhead = new ListNode();
dummyhead.next = head; //新建一个虚拟头结点
ListNode fast = dummyhead; //快慢指针开始都先指向虚拟头结点
ListNode slow = dummyhead;
for(int i = 0;i < n;i++){ //让快指针先走n个
fast = fast.next;
}
while(fast.next != null){
fast = fast.next;//快指针走到尾部之前,两个指针同时移动,此时慢指针指向删除结点的前一个几点
slow = slow.next;
}
slow.next = slow.next.next;
return dummyhead.next;
}
}
思考一个问题就能找到删除结点的前一个结点了。即(若共有i个结点,删除倒数第n个,那么删除的是正数第多少个?找到i 和 n之间的关系即可)
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int lengthA = 0 ,lengthB = 0;
if(curA == null || curB == null){
return null;
}
while(curA.next != null){
lengthA++;
curA = curA.next;
}
while(curB.next != null){
lengthB++;
curB = curB.next;
}
curA = headA;
curB = headB;
if(lengthA >= lengthB){
int k = lengthA - lengthB;
while(k-- != 0){
curA = curA.next;
}
}else{
int k = lengthB - lengthA;
while(k-- != 0){
curB = curB.next;
}
}
while(curA.next != null && curB.next != null && curB.next != curA.next){
curA = curA.next;
curB = curB.next;
}
if(curA.next == null){
return null;
}else{
return curA.next;
}
}
}
大致思路没问题。但是为什么判断AB长短之后就出问题了呢?
搞两个指针。如果up不动,如果down遍历到末尾都没有回到up的时候,那么将up后移,同时把down指向和up同样的位置,再开始一轮这样的操作,直到up.next为空。
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode up = head;
ListNode down = head;
while(up.next != null){ //当up下个结点不是空
while(down.next != up && down.next != null){ //将down移动到无环链表尾或有环链表的最后一个元素
down = down.next;
}
if(down.next == up){ //若是有环链表最后一个
return up;
}
if(down.next == null){ //若是无环链表尾
down = up;
}
up = up.next; //如果一个循环没找到就把两个指针同时往后移一个
down = down.next;
}
return null;
}
}
超时。看讲解。
讲解的太妙了!我的做法是每往后移动一个都要把整个链表遍历一遍。
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;
}
}
博客围绕链表操作展开,涉及两两交换链表节点、删除链表倒数第N个结点、链表相交和环形链表II等问题。记录了解题思路,如用临时结点存储值、计算结点数量等,同时也提出了一些疑惑,如头结点位置、如何找到删除结点的前一个结点等。

被折叠的 条评论
为什么被折叠?



