代码随想录算法训练营第3天 | 链表删除元素、翻转链表
删除链表元素,技巧是设置一个虚拟头节点,这样就可以把原始头节点当做普通节点处理了,最后再返回虚拟头结点的next即可。
题203. 移除链表元素
/**
* 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 removeElements(ListNode head, int val) {
if(head==null){
return null;
}
ListNode vir = new ListNode();
vir.next = head;
ListNode cur1 = vir;
ListNode cur2 = vir.next;
while(cur2!=null){
if(cur2.val==val){
cur1.next = cur2.next;
cur2 = cur1.next;
}else{
cur1=cur2;
cur2=cur2.next;
}
}
return vir.next;
}
}
反转链表
注意:
- 自己模拟一遍过程,注意最后退出循环后要把新的头节点的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 reverseList(ListNode head) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
if(head.next.next==null){
ListNode p1 = head.next;
p1.next = head;
head.next = null;
return p1;
}
ListNode cur1 = head;
ListNode cur2 = head.next;
ListNode cur3 = head.next.next;
return reverse(head,cur1,cur2,cur3);
}
public ListNode reverse(ListNode head,ListNode cur1,ListNode cur2,ListNode cur3){
if(cur3==null){
cur2.next = cur1;
head.next = null;
return cur2;
}else{
cur2.next = cur1;
cur1 = cur2;
cur2 = cur3;
cur3 = cur3.next;
return reverse(head,cur1,cur2,cur3);
}
}
}
//循环
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
if(head.next.next==null){
ListNode p1 = head.next;
p1.next = head;
head.next = null;
return p1;
}
ListNode cur1 = head;
ListNode cur2 = head.next;
ListNode cur3 = head.next.next;
do{
cur2.next = cur1;
cur1 = cur2;
cur2 = cur3;
cur3 = cur3.next;
}while(cur3!=null);
cur2.next = cur1;
head.next = null;
return cur2;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步