链表 1
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) {
// 判断移除头节点的情况,注意是while [7,7,7,7] 7
while(head!=null&&head.val==val) head = head.next;
ListNode cur = head;
while(cur!=null&&cur.next!=null){
if(cur.next.val==val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
那么可不可以 以一种统一的逻辑来移除 链表的节点呢。
其实「可以设置一个虚拟头结点」,这样原链表的所有节点就都可以按照统一的方式进行移除了
/**
* 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) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while(cur.next!=null){
if(cur.next.val==val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummy.next;
}
}
147. 对链表进行插入排序
使用哑节点方便统一操作新链表。pre指针代表已排序好的链表头节点,每次从头遍历,和待插入元素比较:小于则一直往后直到找出下一个节点大于待查节点(cur)的元素即插入点。
/**
* 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 insertionSortList(ListNode head) {
ListNode dummy = new ListNode(-1);
//pre代表已排序完链表的头指针
ListNode pre = dummy, cur = head;
while(cur!=null){
//遍历新链表,若节点元素小于待插入元素则继续,直到找到应插之处的前面一个节点
while(pre.next!=null&&pre.next.val<cur.val) pre = pre.next;
//插入
ListNode save = cur.next;
cur.next = pre.next;
pre.next = cur;
//因为每次pre都要从头比较待插元素
pre=dummy;
//cur继续遍历,断了的线继续连QAQ
cur=save ;
}
return dummy.next;
}
}

浙公网安备 33010602011771号