中转文本

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_25605637/article/details/100549405
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public ListNode removeNthFromEnd(ListNode head, int n) {
	// 考虑到移除链表头节点的情况
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode first = dummy;
    ListNode second = dummy;
    // 移动前面的指针
    for (int i = 1; i <= n + 1; i++) {
        first = first.next;
    }
    // 同步移动2个指针
    while (first != null) {
        first = first.next;
        second = second.next;
    }
    second.next = second.next.next;
    return dummy.next;
}

猜你喜欢

转载自blog.csdn.net/qq_25605637/article/details/100549405