从链接列表的最后一个获取n

发布于 2025-01-22 07:16:39 字数 1724 浏览 3 评论 0原文

我正在做的是,首先我扭转了链接列表,然后实际上我正在尝试获取节点的n个值。问题在于该功能在逆转链接列表后没有做任何事情,并且由于某种原因不会出现错误。

这是我的代码:

#include<stdlib.h>
#include<assert.h>

// 1. Create a linked list first
struct Node {
  int data;
  struct Node* next;
};

// 2. Create traversal function for linked list
void linkedListTraversal(struct Node* ptr) {
  while (ptr != NULL) {
    printf("%d\n", ptr->data);
    ptr = ptr->next;
  }
}

// 3. Write a function to get the node value from the tail of the linked list
int getNode(struct Node* head, int positionFromTail) {
  int value;
  struct Node* prevNode = NULL;
  struct Node* currNode = head;
  struct Node* nextNode;

  while (currNode != NULL) {
    nextNode = currNode->next;
    currNode->next = prevNode;
    prevNode = currNode;
    currNode = nextNode;
  }
  head = prevNode;

  struct Node* ptr = head;
  int count = 0;

  while (ptr != NULL) {
    if (count == positionFromTail) {
      return (ptr->data);
      count = count + 1;
      ptr = ptr->next;
    }

  }
  assert(0);
}

int main() {
  struct Node* head;
  struct Node* second;
  struct Node* third;
  struct Node* fourth;

  head = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  third = (struct Node*)malloc(sizeof(struct Node));
  fourth = (struct Node*)malloc(sizeof(struct Node));

  head->data = 3;
  head->next = second;

  second->data = 2;
  second->next = third;

  third->data = 1;
  third->next = fourth;

  fourth->data = 0;
  fourth->next = NULL;

  linkedListTraversal(head);

  printf("The value of the node is %d", getNode(head, 2));
}

这是我的输出,任何帮助将不胜感激。

3
2
1
0

What I'm doing is that first I reversed the linked list and then actually I'm trying to get the nth value of a node. The problem is that the function isn't doing anything after it reverses the linked list and doesn't give an error for some reason.

Here's my code:

#include<stdlib.h>
#include<assert.h>

// 1. Create a linked list first
struct Node {
  int data;
  struct Node* next;
};

// 2. Create traversal function for linked list
void linkedListTraversal(struct Node* ptr) {
  while (ptr != NULL) {
    printf("%d\n", ptr->data);
    ptr = ptr->next;
  }
}

// 3. Write a function to get the node value from the tail of the linked list
int getNode(struct Node* head, int positionFromTail) {
  int value;
  struct Node* prevNode = NULL;
  struct Node* currNode = head;
  struct Node* nextNode;

  while (currNode != NULL) {
    nextNode = currNode->next;
    currNode->next = prevNode;
    prevNode = currNode;
    currNode = nextNode;
  }
  head = prevNode;

  struct Node* ptr = head;
  int count = 0;

  while (ptr != NULL) {
    if (count == positionFromTail) {
      return (ptr->data);
      count = count + 1;
      ptr = ptr->next;
    }

  }
  assert(0);
}

int main() {
  struct Node* head;
  struct Node* second;
  struct Node* third;
  struct Node* fourth;

  head = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  third = (struct Node*)malloc(sizeof(struct Node));
  fourth = (struct Node*)malloc(sizeof(struct Node));

  head->data = 3;
  head->next = second;

  second->data = 2;
  second->next = third;

  third->data = 1;
  third->next = fourth;

  fourth->data = 0;
  fourth->next = NULL;

  linkedListTraversal(head);

  printf("The value of the node is %d", getNode(head, 2));
}

Here's my output and any help will be appreciated.

3
2
1
0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人骨 2025-01-29 07:16:39

您可以具有无限循环,因为仅当循环中的if语句条件评估以true

while (ptr!=NULL)
{
 if (count == positionFromTail)
 {
  return (ptr->data);
  count = count + 1;
  ptr = ptr->next;
 }


}

重写for for for for for for for ptr 至少例如,

while ( ptr != NULL && positionFromTail-- )
{
    ptr = ptr->next;
}

if ( ptr != NULL )
{
    return ptr->data;
}
else
{
    // return some value
    return  -1;
}

例如参数position> positionfromtail < /代码>应具有未签名的整数类型。否则,您需要检查函数的开头是否具有负值。

退出功能后,请注意您的列表将被打破。调用函数后,MAIN中的指针头将不会更改,但是将更改指针和其他节点指向的数据成员的值。因此,通常您的方法是不正确的。

无需扭转列表即可从列表末端计算的给定位置找到一个元素。

我会以以下方式声明函数

int getNode( const struct Node *head, int pos, int *data );

对于初学者,如果存在具有指定位置的节点或0否则, ,该函数返回1。如果有一个带有指定位置的节点,则存储的值写在“删除参数” data中。

如果参数的值pos不是负面的,则节点的计数是从列表末尾开始的。

这是一个演示程序。

#include <stdlib.h>
#include <stdio.h>

struct Node 
{
    int data;
    struct Node *next;
};

void clear( struct Node **head )
{
    while (*head)
    {
        struct Node *current = *head;
        *head = ( *head )->next;
        free( current );
    }
}

size_t create( struct Node **head, const int a[], size_t n )
{
    clear( head );

    size_t i = 0;

    while (n-- && ( *head = malloc( sizeof( struct Node ) ) ) != NULL )
    {
        ( *head )->data = *a++;
        ( *head )->next = NULL;
        ++i;
        head = &( *head )->next;
    }

    return i;
}

FILE * display( const struct Node *head, FILE *fp )
{
    for (; head != NULL; head = head->next)
    {
        fprintf( fp, "%d -> ", head->data );
    }

    fputs( "null", fp );

    return fp;
}    

int getNode( const struct Node *head, int pos, int *data )
{
    int success = 0;

    if (!( pos < 0 ))
    {
        while (head != NULL && pos--)
        {
            head = head->next;
        }

        if (( success = head != NULL )) *data = head->data;
    }
    else
    {
        const struct Node *current = head;

        for ( ;current != NULL && pos; ++pos )
        {
            current = current->next;
        }

        while (current != NULL )
        {
            head = head->next;
            current = current->next;
        }

        if (( success = pos == 0 )) *data = head->data;
    }

    return success;
}

int main( void )
{
    struct Node *head = NULL;
    const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    create( &head, a, sizeof( a ) / sizeof( *a ) );

    fputc( '\n', display(head, stdout ) );

    for (int i = 0, data; getNode( head, i, &data ); i++)
    {
        printf( "%d: %d; ", i, data );
    }
    putchar( '\n' );

    for (int i = -1, data; getNode( head, i, &data ); i--)
    {
        printf( "%d: %d; ", i, data );
    }
    putchar( '\n' );

    clear( &head );
}

程序输出是

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null

0: 0; 1: 1; 2: 2; 3: 3; 4: 4; 5: 5; 6: 6; 7: 7; 8: 8; 9: 9;
-1: 9; -2: 8; -3: 7; -4: 6; -5: 5; -6: 4; -7: 3; -8: 2; -9: 1; -10: 0;

You can have an infinite loop because the pointer ptr is changed only when the condition of the if statement within the loop evaluates to true

while (ptr!=NULL)
{
 if (count == positionFromTail)
 {
  return (ptr->data);
  count = count + 1;
  ptr = ptr->next;
 }


}

Rewrite the for loop at least for example like

while ( ptr != NULL && positionFromTail-- )
{
    ptr = ptr->next;
}

if ( ptr != NULL )
{
    return ptr->data;
}
else
{
    // return some value
    return  -1;
}

Also the parameter positionFromTail shall have an unsigned integer type. Otherwise you need to check in the beginning of the function whether it has a negative value.

Pay attention to that after exiting the function your list will be broken. The pointer head in main will not be changed after calling the function but the value of the data member next of the node pointed to by the pointer and of other nodes will be changed. So in general your approach is incorrect.

There is no need to reverse the list to find an element at the given position counted from the end of the list.

For starters I would declare the function the following way

int getNode( const struct Node *head, int pos, int *data );

That is the function returns either 1 if there exists a node with the specified position or 0 otherwise. If there is a node with the specified position then the stored value is written in the dereferenced parameter data.

If the value of the parameter pos is not negative then counting of nodes starts from the head otherwise from the end of the list.

Here is a demonstration program.

#include <stdlib.h>
#include <stdio.h>

struct Node 
{
    int data;
    struct Node *next;
};

void clear( struct Node **head )
{
    while (*head)
    {
        struct Node *current = *head;
        *head = ( *head )->next;
        free( current );
    }
}

size_t create( struct Node **head, const int a[], size_t n )
{
    clear( head );

    size_t i = 0;

    while (n-- && ( *head = malloc( sizeof( struct Node ) ) ) != NULL )
    {
        ( *head )->data = *a++;
        ( *head )->next = NULL;
        ++i;
        head = &( *head )->next;
    }

    return i;
}

FILE * display( const struct Node *head, FILE *fp )
{
    for (; head != NULL; head = head->next)
    {
        fprintf( fp, "%d -> ", head->data );
    }

    fputs( "null", fp );

    return fp;
}    

int getNode( const struct Node *head, int pos, int *data )
{
    int success = 0;

    if (!( pos < 0 ))
    {
        while (head != NULL && pos--)
        {
            head = head->next;
        }

        if (( success = head != NULL )) *data = head->data;
    }
    else
    {
        const struct Node *current = head;

        for ( ;current != NULL && pos; ++pos )
        {
            current = current->next;
        }

        while (current != NULL )
        {
            head = head->next;
            current = current->next;
        }

        if (( success = pos == 0 )) *data = head->data;
    }

    return success;
}

int main( void )
{
    struct Node *head = NULL;
    const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    create( &head, a, sizeof( a ) / sizeof( *a ) );

    fputc( '\n', display(head, stdout ) );

    for (int i = 0, data; getNode( head, i, &data ); i++)
    {
        printf( "%d: %d; ", i, data );
    }
    putchar( '\n' );

    for (int i = -1, data; getNode( head, i, &data ); i--)
    {
        printf( "%d: %d; ", i, data );
    }
    putchar( '\n' );

    clear( &head );
}

The program output is

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null

0: 0; 1: 1; 2: 2; 3: 3; 4: 4; 5: 5; 6: 6; 7: 7; 8: 8; 9: 9;
-1: 9; -2: 8; -3: 7; -4: 6; -5: 5; -6: 4; -7: 3; -8: 2; -9: 1; -10: 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文