如何找到从一个单向链表结束第n个元素?元素、链表、结束

2023-09-11 01:53:23 作者:誰伴莪聞荡

下面的函数试图找到第n 为最后一个的单链表元素。

例如:

如果该元素是 8-> 10→5→7-> 2→1→5→4- GT; 10→10 那么结果是 7 来最后一个节点是 7

任何人可以帮助我如何code是工作还是有一个更好,更简单的方法?

 一个LinkedListNode nthToLast(一个LinkedListNode头,INT N){
  如果(头== NULL || N'小于1){
  返回null;
}
  一个LinkedListNode P1 =头;
  一个LinkedListNode P2 =头;
  对于(INT J = 0; J&n种 -  1 ++ j)条{//跳过前面的N-1步
  如果(P2 == NULL){
       返回null; //不是因为列表的大小和其中找到; ñ
   }
  P2 = p2.next;
  }
  而(p2.next!= NULL){
  P1 = p1.next;
  P2 = p2.next;
 }
   返回P1;
 }
 
java 链表删除 Java链表中元素删除的实现方法详解

解决方案

您算法的工作原理是首先创建一个有N个节点除了引用了两个节点的链接列表。因此,在例如,如果N是7,然后它将设置P1至8和p2至4

然后,它将前进每个节点引用到下一个节点的列表,直到P2到达列表中的最后一个元素。再次,在你的例子,这将是当p1为5和p2是10.在这一点上,p1的参照第N到最后一个元素列表中的(由它们和N个节点隔开的属性)。

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are 8->10->5->7->2->1->5->4->10->10 then the result is 7th to last node is 7.

Can anybody help me on how this code is working or is there a better and simpler approach?

LinkedListNode nthToLast(LinkedListNode head, int n) {
  if (head == null || n < 1) {
  return null;
}
  LinkedListNode p1 = head;
  LinkedListNode p2 = head;
  for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
  if (p2 == null) {
       return null; // not found since list size < n
   }
  p2 = p2.next;
  }
  while (p2.next != null) {
  p1 = p1.next;
  p2 = p2.next;
 }
   return p1;
 }

解决方案

Your algorithm works by first creating references to two nodes in your linked list that are N nodes apart. Thus, in your example, if N is 7, then it will set p1 to 8 and p2 to 4.

It will then advance each node reference to the next node in the list until p2 reaches the last element in the list. Again, in your example, this will be when p1 is 5 and p2 is 10. At this point, p1 is referring to the Nth to the last element in the list (by the property that they are N nodes apart).