新聞中心
1.Swap Nodes in Pairs
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode first = head, second = head.next;
head = head.next;
while(second != null){
ListNode third = null;
if(second.next != null){
third = second.next;
}
second.next = first;
if(third == null || third.next == null){
first.next = third;
break;
}else{
first.next = third.next;
first = third;
second = third.next;
}
}
return head;
}
}
LinkedList操作題通解:把要做的操作全列出來,找出相同的部分放進(jìn)循環(huán)里。之后,再處理邊界條件。
不難,大清早就做出來了。相比答案還是復(fù)雜了些。有時間研究研究遞歸版本。
2.Remove Nth Node From End of List
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next == null) return null;
ListNode dummy = new ListNode(0, head);
ListNode tmp = head, tmp2 = dummy;
for(int i = 0; i< n; ++i) tmp = tmp.next;
while(tmp != null){
tmp = tmp.next; tmp2 = tmp2.next;
}
tmp2.next = tmp2.next.next;
return dummy.next; //不能return head,因為head有可能被刪掉了
}
}
思路:先讓它走n個,以后讓慢pointer慢慢跟。
3.Intersection of Two Linked Lists
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tmp1 = headA, tmp2 = headB;
while(tmp1 != tmp2){
tmp1 = tmp1 == null? headB: tmp1.next;
tmp2 = tmp2 == null? headA: tmp2.next;
}
return tmp1;
}
}
相交鏈表核心:兩個指針分別從兩個鏈表的頭開始,向前遍歷。如果其中一個走完了,那么換另一個鏈表繼續(xù)走,直到相遇為止。
相遇之后,可能都為null(則不相交);如果都指向同一個值,就是他們相交的開始。
當(dāng)然,還有笨蛋方法(但效率與此代碼相同)。
- 先求出兩個鏈表長度。
- 移動長鏈表,讓兩個鏈表在同一起跑線上。
- 同時移動兩個指針,直到他們相遇/不相遇。如果不相遇,在最后return null即可。
4.Linked List Cycle II
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null) return null;
ListNode slow = head, fast = head;
while(true){
slow = slow.next;
if(fast == null || fast.next == null) return null;
fast = fast.next.next;
if(slow == fast) break;
}
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
環(huán)形鏈表(找出循環(huán)的開端)核心:用fast,slow兩指針,fast每次走兩個,slow走一個。當(dāng)它們相遇時,讓兩指針每次挪一格。相遇的地方就是循環(huán)的開始,因為x = z(見下文)。
算法解釋:見代碼隨想錄
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
分享文章:第三天:反轉(zhuǎn)鏈表遞歸寫法需要鞏固-創(chuàng)新互聯(lián)
分享路徑:http://www.dlmjj.cn/article/cejddh.html