leetcode面试题02.07 链表相交
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode start_1 = headA;
ListNode start_2 = headB;
int length_1 = 0;
int length_2 = 0;
int dis;
while(start_1 != null){
start_1 = start_1.next;
length_1++;
}
//将start_1挪回起始位置
start_1 = headA;
while(start_2 != null){
start_2 = start_2.next;
length_2++;
}
//将start_2挪回起始位置
start_2 = headB;
if(length_1 > length_2){dis = length_1 - length_2;}else {dis = length_2 - length_1;}
if (length_1 > length_2){
while(dis > 0){
start_1 = start_1.next;
dis--;
}
}
else{
while(dis > 0){
start_2 = start_2.next;
dis--;
}
}
while(start_1 != start_2){
start_1 = start_1.next;
start_2 = start_2.next;
}
return start_1;
}
}
leetcode 142 环形链表
本题采用快慢指针的思想判断单链表是否存在环。注意循环的终止条件是fast != null && fast.next != null。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null ){
return null;
}
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}
leetcode 24 两两交换链表中的节点
注意cur指针一定要先指向待交换的两个节点的前一个节点的位置。并且利用虚拟头节点。
注意循环退出条件:cur.next != null (链表节点数为偶数) ;cur.next.next != null(链表节点数为奇数)。否则会出现空指针异常(null.next 是错误的)。还需要注意在cur.next改变之前应该用临时变量temp保存其原本的next中存放的地址,否则之后会无法找到其原本的后续节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1,head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
ListNode temp = cur.next;
ListNode temp2 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp;
temp.next = temp2;
//操作下一组两两节点对
cur = cur.next.next;
}
return dummy.next;//即链表的头节点
}
}