删除链表特定数据/反转链表
删除链表特定数据
1.特别处理:空链表
2.特别处理:链表的前几个元素都是val元素怎么办
3.普适情况:
while(cur != null){//遍历结束的条件cur!=null
if(cur.val==val){ //val数在中间
pre.next=cur.next;
}
pre = cur;
cur = cur.next; //遍历模版
}//链表的开头肯定不是val
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null){//实例2开头为空
return head;
}
while(head!=null&&head.val==val){//直接删除第一个结点
head=head.next;
}
ListNode cur=head;//当前结点
ListNode pre=head;//当前结点
//当前获得数组的头几个元素,不是val
while(cur != null){//遍历结束的条件是next== null
if(cur.val==val){ //val数在中间
pre.next=cur.next;
}
pre = cur;
cur = cur.next;
}//链表的开头不是val
return head;//返回列表的头结点
}
}
反转链表
真的想不到啊
初始化:
ListNode prev = null;
ListNode cur = head;
ListNode temp = null;
1.pre前一个结点
2.cur当前结点,当前结点的next值指向前一个结点
3.temp保存当前结点之前的next值用于遍历
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
// 双指针
ListNode prev = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {
temp = cur.next;// 保存下一个节点
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}