链表之增加头结点的前缀节点
? Leetcode203删除链表元素
head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。 public ListNode removeElements(ListNode head, int val) { ListNode prefinalHead=new ListNode(-1,head); ListNode preHead=prefinalHead; while(head!=null){ if(head.val==val){ preHead.next=head.next; }else{ preHead=preHead.next; } head=head.next; } return prefinalHead.next; }Leetcode24两两交换链表中的节点
public ListNode swapPairs(ListNode head) { if(head==null){//没元素 return null; } if(head.next==null){//只有一个元素 return head; } ListNode pre=head; ListNode post=head.next; ListNode finallastpre=new ListNode(-1,head); ListNode lastpre=finallastpre; while(pre!=null){ if(post==null){//最后只剩一个节点 pre=pre.next; }else{ ListNode temp=post.next; post.next=pre; lastpre.next=post; pre.next=temp; lastpre=pre; pre=pre.next; if(temp!=null){ post=temp.next; }else{ post=null; } } } return finallastpre.next; }Leetcode19删除链表的倒数第N个结点
n 个结点,并且返回链表的头结点 public ListNode removeNthFromEnd(ListNode head, int n) { ListNode prefinalHead=new ListNode(-1,head); ListNode preHead=prefinalHead; ListNode fast=head; ListNode slow=head; for(int i=1;i<n;i++){ fast=fast.next; } while(fast.next!=null){ slow=slow.next; fast=fast.next; preHead=preHead.next; } preHead.next=slow.next; return prefinalHead.next; }