目录🔥🔥
⚡️⚡️1.剑指offer06.从尾到头打印链表⚡️⚡️
OJ:OJ链接🪢🪢
1.1题目描述💨💨
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
1.2思考过程💨💨
1.3代码 💨💨
1.3.1栈方法💨💨
public int[] reversePrint(ListNode head) {
if(head==null){
return new int[0];
}
Stack<Integer> stack=new Stack<>();
ListNode cur=head;
while(cur!=null){
stack.push(cur.val);
cur=cur.next;
}
int size=stack.size();
int []ret = new int [size];
for(int i=0;i<size;i++){
ret[i]=stack.pop();
}
return ret;
}
要从尾到头打印链表,如果我们用栈来做,发现他先进后出的特点,正适合我们的需求,我们只需依次将链表的val值入栈,完了之后,依次出栈,就能从尾到头输出了。
1.3.2计数器法💨💨
public int[] reversePrint(ListNode head) {
int count =0;
ListNode cur=head;
while(cur!=null){
count++;
cur=cur.next;
}
int[] ret=new int[count];
cur=head;
for(int i=count-1;i>=0;i--){
ret[i]=cur.val;
cur=cur.next;
}
return ret;
}
由于最后我们需要将翻转过来的链表的值全部放到一个数组中,我们就可以定义一个计数器count,遍历数组,令count自增,我们就得到了链表的长度,往最终的数组中放时,我们可以令i从count-1开始往下减,而链表从头往后遍历,这样也能得到翻转的效果。
⚡️⚡️2.剑指offer24.反转链表⚡️⚡️
OJ:OJ链接🪢🪢
2.1题目描述💨💨
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
2.2思考过程💨💨
2.3代码💨💨
2.3.1栈方法💨💨
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
Stack<ListNode> stack=new Stack<>();
ListNode cur=head;
while(cur!=null){
stack.push(cur);
cur=cur.next;
}
head=stack.pop();
cur=head;
while(!stack.empty()){
ListNode tmp=stack.pop();
tmp.next=null;
cur.next=tmp;
cur=cur.next;
}
cur.next=null;
return head;
}
要反转列表我们同样可以借助栈来做,首先将链表遍历,然后依次入栈,最后我们定义一个前驱来,先出一个保存在前驱中,在依次遍历出栈,把新的链表链接起来即可
2.3.2双指针法💨💨
public ListNode reverseList(ListNode head) {
ListNode prev=null;
ListNode cur=head;
ListNode next=null;
while(cur!=null){
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
我们也可以直接定义前驱和后驱,遍历一遍,直接修改它们的指向,一次遍历就能反转。
2.3.3递归法💨💨
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode node=reverseList(head.next);
head.next.next=head;
head.next=null;
return node;
}
注意 :n1 的下一个节点必须指向∅。如果忽略了这一点,链表中可能会产生环。
⚡️⚡️3.剑指offer35.复杂链表的复制⚡️⚡️
OJ:OJ链接🪢🪢
3.1题目描述💨💨
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
3.2思考过程💨💨
3.3代码💨💨
class Solution {
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
HashMap<Node,Node> map=new HashMap<>();
Node cur=head;
while(cur!=null){
Node node=new Node(cur.val);
map.put(cur,node);
cur=cur.next;
}
cur=head;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
return map.get(head);
}
}
首先我们遍历一遍链表,new 新的节点。用map将原来的所有节点与新的节点一一对应起来,存储在map中,然后用get()方法对他们进行访问,把一个个节点全都串起来。