LintCode—刪除連結串列中倒數第n個節點(174)
阿新 • • 發佈:2019-02-15
資料結構—線性結構—連結串列:(刪除連結串列中倒數第n個元素)
一、題目:給定一個連結串列,刪除連結串列中倒數第n個節點,返回連結串列的頭節點。(連結串列中的節點個數大於n)
樣例:給出連結串列1->2->3->4->5->null和 n = 2.刪除倒數第二個節點之後,這個連結串列將變成1->2->3->5->null.二、分析:
需要考慮的點:
1、連結串列只有1個元素,且n=1;如1->null,n=1;
2、刪除元素為連結串列的頭節點;
3、O(n)時間複雜度,單項鍊表,只走一遍;
三、程式碼:
** * Definition for ListNode */ public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class Solution { /** * @param head: The first node of linked list. * @param n: An integer * @return: The head of linked list. */ public ListNode removeNthFromEnd(ListNode head, int n) { ListNode probeNode = new ListNode(0); ListNode currentNode = new ListNode(0); ListNode headNode = new ListNode(0); probeNode.next = head; int i; if(probeNode.next != null){ for(i = 0; i <= n; i++){ probeNode = probeNode.next; } currentNode.next = head; headNode = currentNode; while(probeNode != null){ probeNode = probeNode.next; currentNode = currentNode.next; } currentNode.next = currentNode.next.next; }else{ headNode.next = null; } return headNode.next; } }