链表基本操作(1)

2020/04/01 算法 链表

删除链表中的节点,删除链表的倒数第N个节点,反转链表

删除链表中的节点

请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 现有一个链表 – head = [4,5,1,9],它可以表示为:

思路

删除某个节点的操作即使得node的next指针指向node的下下个节点的内存地址即可

代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

[题目来源]https://leetcode-cn.com/problems/delete-node-in-a-linked-list/

删除链表的倒数第N个节点

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
思路
  • 整体思路是让前面的指针先移动n步,之后前后指针共同移动直到前面的指针到尾部为止
  • 首先设计哨兵pre
  • 设预先指针 pre 的下一个节点指向 head,设前指针为 start,后指针为 end,二者都等于 pre
  • start 先向前移动n步
  • 之后 start 和 end 共同向前移动,此时二者的距离为 n,当 start 到尾部时,end 的位置恰好为倒数第 n 个节点
  • 因为要删除该节点,所以要移动到该节点的前一个才能删除,所以循环结束条件为 start.next != null
  • 删除后返回 pre.next,为什么不直接返回 head 呢,因为 head 有可能是被删掉的点
  • 时间复杂度:O(n)
代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //哨兵节点
        ListNode pre = new ListNode(0);
        //哨兵节点指向头节点
        pre.next = head;
        //新增两个指针,start指针先前进n步,使得start与end间隔为n
        ListNode start = pre, end = pre;
        while(n != 0) {
            start = start.next;
            n--;
        }
        //start和end指针同步前进直到start指针指向null(结尾)
        while(start.next != null) {
            start = start.next;
            end = end.next;
        }
        //此时将end的next指针指向end的下下一个节点的内存地址即删除了倒数第n个节点
        end.next = end.next.next;
        return pre.next;

    }
}

[题目来源]https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/

反转链表

反转一个单链表

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路

改变指针的方向即可

代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
       if(head == null) return null;
    
        ListNode pre = null;
        ListNode curr = head;
        
        while(curr != null){
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
       
        return pre;
    }
}

[题目来源]https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

Search

    Table of Contents