LintCode之鏈表倒數第n個節點
阿新 • • 發佈:2017-10-26
first bsp urn val ram tco .cn cnblogs 1-1
題目描述:
我的代碼:
1 /** 2 * Definition for ListNode. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int val) { 7 * this.val = val; 8 * this.next = null; 9 * } 10 * } 11 */ 12 13 14 public class Solution { 15 /* 16 * @param head: The first node of linked list.17 * @param n: An integer 18 * @return: Nth to last node of a singly linked list. 19 */ 20 public ListNode nthToLast(ListNode head, int n) { 21 // write your code here 22 if(head == null) { 23 return null; 24 } 25 ListNode h = new ListNode(-1);26 //倒置單鏈表 27 while(head != null) { 28 ListNode node = new ListNode(head.val); 29 if(h.next == null) { 30 h.next = node; 31 }else { 32 node.next = h.next; 33 h.next = node; 34 } 35 if(head.next != null) { 36 head = head.next; 37 }else { 38 head = null; 39 } 40 } 41 h = h.next; 42 //取得倒置後的單鏈表的第n個節點,這個節點就是原鏈表的倒數第n個節點 43 for(int i=1; i<n; i++) { 44 h = h.next; 45 } 46 ListNode node = new ListNode(h.val); 47 return node; 48 } 49 }
總結:因為這是單鏈表,無法像雙鏈表一樣輕松的獲得一個節點的前一個節點,所以,我就把這個單鏈表倒置,倒置後的單鏈表的第n個節點就是倒置前的單鏈表的倒數第n個節點,這樣就能通過遍歷獲得倒數第n個節點了。
LintCode之鏈表倒數第n個節點