• LeetCode(19): Remove Nth Node From End of List


    Remove Nth Node From End of List:Given a linked list, remove the nth node from the end of list and return its head.For example:

    Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.

    题意:删除给定链表倒数第n个结点。

    思路:其实本题比较常规的思路是先遍历链表求得链表的长度,然后在进行删除操作。另外一种思路是定义两个指针left和right,right先移动n步,如果right为null,则表示要删除的是头结点,此时直接返回head.next即可。如果first指针不为null,则两个指针一起移动,直到right为最后一个结点为止,left指向的即是要删除结点的前一个结点,可以直接执行left.next=left.next.next操作即可删除倒数第n个结点。

    代码:

    public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head==null) return null;
            ListNode p = head;
            ListNode q = head;
            
            for(int i=0;i<n;i++){
                q=q.next;
            }
            if(q==null){
                head = head.next;
                p = null;
                return head;
            }
            while(q.next!=null){
                p = p.next;
                q = q.next;
            }
            ListNode temp = p.next.next;
            p.next = temp;
            return head;
             
        }
  • 相关阅读:
    通俗理解时空效应,感受质量、空间与时间的关系_番外篇
    第四十三象 丙午
    第四十二象 乙巳
    第四十一象 甲辰
    第四十象 癸卯
    ServiceComb简介
    Spring-Session实现Session共享
    SpringBoot整合ActiveMQ
    Hbase配置运行
    KafKa配置运行
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5128242.html
Copyright © 2020-2023  润新知