1 class ListNode 2 { 3 int val; 4 ListNode next; 5 ListNode(int x) 6 { 7 val = x; 8 } 9 } 10 public class NthNodeFromEnd { 11 public ListNode removeNthFromEnd(ListNode head, int n) 12 { 13 ListNode p = head; 14 ListNode q = head; 15 for(int i = 0; i < n ; i++) 16 { 17 p = p.next; 18 } 19 if(p == null)//如果p==null,说明倒数第n个就是第一个节点,即头结点。 20 { 21 head = head.next; 22 return head; 23 } 24 while(p.next != null) 25 { 26 p = p.next; 27 q = q.next; 28 } 29 if(q.next != null) 30 { 31 q.next = q.next.next; 32 } 33 34 return head; 35 } 36 public ListNode removeNthFromEnd2(ListNode head, int n) 37 { 38 //因为要删掉倒数第n个节点,那就必须找到倒数第n+1个节点 39 //如果倒数第n正好是头结点,那么头结点前面没有节点了很麻烦,我们可以设置一个节点作为头结点之前的节点 40 //设置一个头结点,这样就不用单独对原始头结点处理了 41 ListNode dumy = new ListNode(0); 42 dumy.next = head; 43 ListNode p = dumy; 44 ListNode q = dumy; 45 for(int i = 0; i < n; i ++) 46 { 47 p = p.next; 48 } 49 while(p.next!=null) 50 { 51 p = p.next; 52 q = q.next; 53 } 54 q.next = q.next.next; 55 return dumy.next; 56 } 57 //找倒数第n个节点 58 public ListNode findNthFromEnd(ListNode head, int n) 59 { 60 ListNode p = head; 61 ListNode q = head; 62 for(int i = 0; i < n-1; i ++) 63 { 64 p = p.next; 65 } 66 while(p.next!=null) 67 { 68 p = p.next; 69 q = q.next; 70 } 71 return q; 72 } 73 74 public static void main(String[] args) 75 { 76 NthNodeFromEnd rn = new NthNodeFromEnd(); 77 ListNode n1 = new ListNode(1); 78 ListNode n = rn.removeNthFromEnd(n1, 1); 79 System.out.println(rn.findNthFromEnd(n1, 1).val); 80 if(n == null) 81 { 82 System.out.println(n); 83 } 84 while(n!= null) 85 { 86 System.out.println(n.val); 87 n = n.next; 88 } 89 } 90 }
时间: 2024-10-26 20:47:10