删除结点问题
题意:删除链表中等于给定值 val 的所有节点。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
class Solution {
public ListNode removeElements(ListNode head, int val) {
//设置虚节点和不设置虚节点:好处是将头结点不用单独讨论
//对删讨论头结点
while(head!=null&&head.val==val){
head=head.next;
}
//出来的head可能是null
if(head==null) return null;
//此时的head不等于val
ListNode pre=head;
ListNode cur=head.next;
//删除其他区域的
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
}else{
pre=cur;
}
//cur每次都是要移动的
cur=cur.next;
}
return head;
}
}
public ListNode removeElements(ListNode head, int val) {
//设置虚节点和不设置虚节点:好处是将头结点不用单独讨论
if(head==null) return head;
//虚节点
ListNode dummy=new ListNode(-1,head);
ListNode pre=dummy;
ListNode cur=head;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
}else{
pre=cur;
}
cur=cur.next;
}
//虚节点的下一个结点一定是头结点
return dummy.next;
}
}
反链表
题意:反转一个单链表。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
class Solution {
public ListNode reverseList(ListNode head) {
//利用栈
//双指针
if(head==null) return null;
Stack<ListNode> s=new Stack<>();
while(head!=null){
s.push(head);
head=head.next;
}
ListNode last=s.pop();
head=last;//记录新头
while(!s.isEmpty()){
last.next=s.pop();
last=last.next;
}
//last来到原首结点
last.next=null;
return head;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
//利用栈
//三指针
if(head==null||head.next==null) return head;
ListNode pre=null;
ListNode cur=head;
ListNode temp=null;
while(cur!=null){
temp=cur.next;//寄存
cur.next=pre;//改变指针
pre=cur;
cur=temp;
}
return pre;
}
}
相邻结点交换
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
用虚节点,交换的时候可以用它指向下一次交换后的第一个结点
class Solution {
public ListNode swapPairs(ListNode head) {
//是否直接用temp来调节
if(head==null||head.next==null) return head;
//初始化虚节点
ListNode dummy=new ListNode(-1,head);
ListNode cur=dummy;
while(cur.next!=null&&cur.next.next!=null){
//缓存
ListNode temp=cur.next.next.next;
//交换
cur.next=cur.next.next;
head.next.next=head;
head.next=temp;
cur=head;
head=temp;//新交换点
}
return dummy.next;
}
}