leetcode-鏈表-19

/** * <p>給你一個鏈表,刪除鏈表的倒數第&nbsp;<code>n</code><em>&nbsp;</em>個結點,並且返回鏈表的頭結點。</p> * * <p>&nbsp;</p> * * <p><strong>示例 1:</strong></p> * <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" style="width: 542px; height: 222px;" /> * <pre> * <strong>輸入:</strong>head = [1,2,3,4,5], n = 2 * <strong>輸出:</strong>[1,2,3,5] * </pre> * * <p><strong>示例 2:</strong></p> * * <pre> * <strong>輸入:</strong>head = [1], n = 1 * <strong>輸出:</strong>[] * </pre> * * <p><strong>示例 3:</strong></p> * * <pre> * <strong>輸入:</strong>head = [1,2], n = 1 * <strong>輸出:</strong>[1] * </pre> * * <p>&nbsp;</p> * * <p><strong>提示:</strong></p> * * <ul> * <li>鏈表中結點的數目爲 <code>sz</code></li> * <li><code>1 &lt;= sz &lt;= 30</code></li> * <li><code>0 &lt;= Node.val &lt;= 100</code></li> * <li><code>1 &lt;= n &lt;= sz</code></li> * </ul> * * <p>&nbsp;</p> * * <p><strong>進階:</strong>你能嘗試使用一趟掃描實現嗎?</p> * <div><div>Related Topics</div><div><li>鏈表</li><li>雙指針</li></div></div><br><div><li>👍 1953</li><li>👎 0</li></div> */ //leetcode submit region begin(Prohibit modification and deletion) /** * 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 dummy = new ListNode(0); dummy.next= head; ListNode countP = head; int len =0; while(countP!=null){ len++; countP=countP.next; } System.out.println("len " +len); int currIndex = 0; int removeIndex = len+1-n-1; System.out.println("removeIndex " +removeIndex); ListNode curr = dummy; while(curr!=null){ if(currIndex==removeIndex){ curr.next=curr.next.next; return dummy.next; }else{ currIndex++; curr=curr.next; } } return dummy.next; } } //leetcode submit region end(Prohibit modification and deletion)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章