链表
剑指 Offer 52. 两个链表的第一个公共节点
利用set集合不重复的特性,先后将两个链表的值存入set中,后者若add失败。则返回此公共节点
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
ListNode res = null;
while(headA != null){
set.add(headA);
headA = headA.next;
}
while(headB != null){
if(!set.add(headB)){
res = headB;
break;
}
headB = headB.next;
}
return res;
}
剑指 Offer 24. 反转链表
pre和cur同时前进,不断改变节点间的指针方向
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode tmp = null;
while(cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
剑指 Offer 22. 链表中倒数第k个节点
利用ArrayList保存链表值,get返回具体索引值即可
public ListNode getKthFromEnd(ListNode head, int k) {
ArrayList<ListNode> array = new ArrayList<>();
ListNode listNode = head;
while(listNode != null){
array.add(listNode);
listNode = listNode.next;
}
return array.get(array.size() - k);
}
剑指 Offer 18. 删除链表的节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
注意约束条件和循环判断条件是判断cur.next
public ListNode deleteNode(ListNode head, int val) {
if(head == null){
return head;
}
if(head.val == val){
return head.next;
}
ListNode cur = head;
while(cur.next != null && cur.next.val != val){
cur = cur.next;
}
if(cur.next != null)
cur.next = cur.next.next;
return head;
}
剑指 Offer 06. 从尾到头打印链表
stack栈先进后出
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
int val = 0;
int[] list = new int[stack.size()];
while(!stack.empty()){
list[val++] = stack.pop();
}
return list;
}
剑指 Offer 35. 复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
来自力扣解题区大佬@Markus的解答
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TK5caN3k-1596075565142)(https://pic.leetcode-cn.com/7a70fbac7677a9a1cd31d404a0ad2d9dc3d92ead30b5e741bb2459dea2077523-%E5%9B%BE%E8%A7%A3%20(2)].png)
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
copy(head);
randomDirect(head);
return reList(head);
}
//拷贝链表
private void copy(Node head){
while(head!=null){
Node cloneNode = new Node(head.val);
Node nextNode = head.next;
head.next = cloneNode;
cloneNode.next = nextNode;
head = cloneNode.next;
}
}
//指定随机指针
private void randomDirect(Node head){
while(head!=null){
Node cloneNode = head.next;
if(head.random!=null){
Node direct = head.random;
cloneNode.random = direct.next;
}
head = cloneNode.next;
}
}
//重新连接 链表
private Node reList(Node head){
Node cloneNode = head.next;
Node cloneHead = cloneNode;
head.next = cloneNode.next;
head = head.next;
while(head!=null){
cloneNode.next = head.next;
head.next = head.next.next;
head = head.next;
cloneNode = cloneNode.next;
}
return cloneHead;
}
}