两两交换链表节点
首先想到了递归方法 如果当前节点==null 或当前节点.next==null 则可以退出方法。 注意 return头结点即第二个节点。
class Solution {
public ListNode swapPairs(ListNode head) {
//退出递归
if(head == null || head.next==null ){
return head;
}
ListNode second = head.next;
ListNode third = swapPairs(second.next);
head.next = third;
second.next = head;
return second;
}
}
虚拟头结点。考虑将设置一个虚拟头结点。循环每次走到下下个节点上。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dumyhead = new ListNode(-1);
dumyhead.next = head;
ListNode cur = dumyhead;
ListNode temp; //临时节点
ListNode firstNode;
ListNode secondNode;
while(cur.next!=null &&cur.next.next!=null){
temp = cur.next.next.next;
firstNode =cur.next;
secondNode = cur.next.next;
cur.next = secondNode;
secondNode.next = firstNode;
firstNode.next = temp;
cur = cur.next.next;
}
return dumyhead.next;
}
}
19 删除倒数第n个节点
使用快慢指针法。
快指针比慢指针提前走n步
考虑到只有一个元素 删除倒数第一个的情况那么就要创建虚拟头节点。
创建虚拟头节点 且快慢指针初始都指向虚拟节点
注意 返回虚拟节点的下一个。如果直接返回头结点会出bug,当只有一个元素时,没有成功删除。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dumyHead = new ListNode(-1);
dumyHead.next = head;
ListNode fast = dumyHead;
ListNode slow = dumyHead;
int num = 0;
while(fast.next!=null){
fast = fast.next;
if(num<n){
num++;
}else{
slow = slow.next;
}
}
slow.next = slow.next.next;
return dumyHead.next;
}
}
链表相交
考虑两个链表中 如果相交则最后几位相同 没有相交后再分开的场景 没有相交后成环的场景
思路:两个链表求出size
/**
* 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 curA = headA;
ListNode curB = headB;
int lenA = 0, lenB = 0;
while (curA != null) { // 求链表A的长度
lenA++;
curA = curA.next;
}
while (curB != null) { // 求链表B的长度
lenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
//1. swap (lenA, lenB);
int tmpLen = lenA;
lenA = lenB;
lenB = tmpLen;
//2. swap (curA, curB);
ListNode tmpNode = curA;
curA = curB;
curB = tmpNode;
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap-- > 0) {
curA = curA.next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != null) {
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}