删除链表的倒数第n个节点,双指针实现

 

/**

 * 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 removeNthFromEnd(ListNode head, int n) {

        ListNode h,q,r,t;

        h=new ListNode();

        h.next=head;

        q=t=h;

        r=h.next;

        for(int i=0;i<n;i++){

            t=t.next;

        }

        while(t.next!=null){

            t=t.next;

            q=q.next;

            r=r.next;

        }

 

        q.next=r.next;


 

        return h.next;

    }

}

相关文章:

  • 2022-12-23
  • 2021-09-24
  • 2021-11-29
  • 2021-11-05
  • 2022-12-23
  • 2021-04-25
  • 2021-11-27
  • 2021-07-28
猜你喜欢
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
  • 2021-04-01
相关资源
相似解决方案