24. Swap Nodes in Pairs - 力扣(LeetCode)
1.遍历何时结束?
分为奇数偶数个节点两种情况
设置一个虚拟头结点phead
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
//
ListNode phead=new ListNode(-1,head);
//添加phead是因为2-1-3-4 操作1-3-4为1-4-3时,我们的pre要指向1
ListNode pre=phead;
ListNode cur=head;
while(cur!=null&&cur.next!=null)//剩一个节点的情况和
{
pre.next=cur.next;
ListNode temp=cur.next.next;
cur.next.next=cur;
cur.next=temp;
//调换完毕
pre=cur;
cur=cur.next;
}
return phead.next;
}
}
递归方式 感觉递归就是不断地把问题分解,直到最底层
// 递归版本
class Solution {
public ListNode swapPairs(ListNode head) {
// base case 退出提交
if(head == null || head.next == null) return head;
// 获取当前节点的下一个节点
ListNode next = head.next;
// 进行递归
ListNode newNode = swapPairs(next.next);
// 这里进行交换
next.next = head;
head.next = newNode;
return next;
}
}
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
这道题和上道题的交换两节点相似,都使用了虚拟头结点,因为我们有一个对节点的操作时,都要操纵当前节点的前一个节点的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 removeNthFromEnd(ListNode head, int n) {
if(head==null)
return head;
if(head.next==null&&n==1)
return null;
//至少有两个节点
ListNode l=head;
ListNode f=head;
ListNode phead=new ListNode(0,head);
ListNode pre=phead;
while(n!=0)
{
f=f.next;
n--;
}
while(f!=null)
{
pre=pre.next;
l=l.next;
f=f.next;
}
pre.next=l.next;
return phead.next;
}
}
面试题 02.07. 链表相交 - 力扣(LeetCode)
"尾端对齐思想"
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//单向链表最大的问题在于只能单向遍历 因此从后向前遍历行不通
ListNode preA=headA;
ListNode preB=headB;
ListNode curA=headA;
ListNode curB=headB;
int lenA=0;
int lenB=0;
int gap=0;
while(preA!=null)
{
preA=preA.next;
lenA++;
}
while(preB!=null)
{
preB=preB.next;
lenB++;
}
if(lenA>lenB)
{
//A为长链表
gap=lenA-lenB;
while(gap!=0)
{
curA=curA.next;
gap--;
}
while(lenB!=0)
{
if(curA==curB)
return curA;
curA=curA.next;
curB=curB.next;
lenB--;
}
}else{
gap=lenB-lenA;
while(gap!=0)
{
curB=curB.next;
gap--;
}
while(lenA!=0)
{
if(curA==curB)
return curA;
curA=curA.next;
curB=curB.next;
lenA--;
}
}
return null;
}
}