力扣刷题日记——链表

文章目录

      • 移除链表元素
      • 反转链表
      • 两两交换链表中的节点

移除链表元素

力扣刷题日记——链表_第1张图片

class Solution {
    public ListNode removeElements(ListNode head, int val) {
            while(head !=null && head.val == val){
                head=head.next;
            }
            if(head==null){
                return head;
            }
            ListNode pre = head;
            ListNode cur = head.next;
            while(cur != null){
                if(cur.val==val){
                    pre.next=cur.next;
                }else{
                    pre=cur;
                  
                }
                  cur=cur.next;//判断下一个
            }
            return head;
    }
}

反转链表

力扣刷题日记——链表_第2张图片

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        ListNode temp = null;
        while (cur != null) {
            temp = cur.next;// 保存下一个节点
            cur.next = prev;//将指针指向pre节点	
            prev = cur;//将pre指针移向下一个节点
            cur = temp;//讲cur指针指向下一个节点
        }
        return prev;//最后pre指针指向的就是最后一个节点。
    }
}

两两交换链表中的节点

力扣刷题日记——链表_第3张图片

// 虚拟头结点
class Solution {
  public ListNode swapPairs(ListNode head) {

    ListNode dummyNode = new ListNode();//虚拟头结点
    dummyNode.next = head;
    ListNode prev = dummyNode;

    while (prev.next != null && prev.next.next != null) {
      ListNode temp = head.next.next; // 缓存 next
      prev.next = head.next;          // 将 prev 的 next 改为 head 的 next
      head.next.next = head;          // 将 head.next(prev.next) 的next,指向 head
      head.next = temp;               // 将head 的 next 接上缓存的temp
      prev = head;                    // 步进1位
      head = head.next;               // 步进1位
    }
    return dummyNode.next;
  }
}

做了三道链表题下来,个人链表题感觉就是要分清楚指针的指向,搞清楚操作顺序,明白每个节点都存有 val值和指向下一个节点的指针

你可能感兴趣的:(链表,leetcode,数据结构)