- 移除链表元素
- 反转链表
。。。补充中
第1题:移除链表元素 【核心:添加虚拟节点】
题意:删除链表中等于给定值 val 的所有节点。
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val){
this.val = val;
}
}
public class Solution {
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
ListNode listNode1 = new ListNode(2);
ListNode listNode2 = new ListNode(6);
ListNode listNode3 = new ListNode(3);
listNode.next=listNode1;
listNode.next.next = listNode2;
listNode.next.next.next=listNode3;
ListNode listNode4 = new Solution().removeNode(listNode, 6);
System.out.println(listNode4.next.next.val);
}
public ListNode removeNode(ListNode head, int n){
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
while (cur.next != null){
if (cur.next.val == n){
cur.next = cur.next.next;
}else {
cur = cur.next;
}
}
return header.next;
}
}
206. 反转链表 【无敌双指针-需要前置节点+tmp节点】
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
public ListNode reverseList(ListNode head){
ListNode cur = null;
ListNode pre = head;
while (pre != null){
ListNode tmp = pre.next;
pre.next = cur;
cur = pre;
pre = tmp;
}
return cur;
}