2022年8月12日 星期五

19. Remove Nth Node From End of List

給定一串ListNode和整數,ListNode的序號為由大到小,刪除整數所指定的序號節點。

https://leetcode.com/problems/remove-nth-node-from-end-of-list/







範例
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]

嘗試使用遞迴來解決,每個遞還方法都會回傳自己的序號,當序號和n相同時,表示該節點須刪除。

寫成程式碼如下

	public ListNode removeNthFromEnd(ListNode head, int n) {
		int now = getListNodeNum(head, n);
		//now == n 表示刪除首欄,直接回傳head.next
		if (now == n) {
			return head.next;
		}
		return head;
	}

	public int getListNodeNum(ListNode head, int n) {

		if (head.next == null) {
			//沒有下一個節點,表示為最後的節點,序號為1
			return 1;
		} else {
			//取到下一個節點的序號
			int now = getListNodeNum(head.next, n);
			//若序號 = n 表示需刪除此節點
			if (now == n) {
				head.next = head.next.next;
			}
			//回傳自身的序號
			return now + 1;
		}
	}

沒有留言:

張貼留言