【问题标题】:How does Linked List function to make another linked list with different order of elements. Explanation pleaseLinked List 如何创建具有不同元素顺序的另一个链表。请解释
【发布时间】:2020-02-17 20:31:53
【问题描述】:
struct node* question4(struct node *list){ //list = 66, 9, 14, 52, 87, 14, 17
      struct node* a = list; //a = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* b = list; //b = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* c;
      if(a == NULL) return NULL; // a is not NULL it's pointing to 66
      while(a->next != NULL) // run until a points to the last element (17) 
            a = a->next;
      a->next = b; //next element of 17 points to b (which is 66). 
      c = b->next; // c points to what b is pointing to next which is 9. 
      b -> next = NULL; // next element of b is NULL(instead of 14). what happens here?
      return c;
}

所以a连接到b。所以a的元素是这样的? 66->9->14->52->87->14->17->66->9->14->52->87->14->17

而 b 只是 66->9->NULL?

c 是 9->14->52->87->14->17?或 9->14->52->87->14->17->66 ?为什么?

我目前正在学习链表,谢谢大家的帮助!

【问题讨论】:

  • b->next 基本上是通过用NULL 替换该指针来破坏原始链表。然后该函数返回列表的剩余部分。

标签: c linked-list rotation singly-linked-list


【解决方案1】:

程序将链表的头部向右移动一个元素,并将原来的第一个元素循环回末尾。您大部分都正确地遵循了,最后几行如下:

a->next = b;

这会将原始最后一个元素链接到原始第一个元素,即创建一个链接 17->66。

c = b->next;

c这里用来存放新的head元素。由于b 指向原来的头,而我们希望第二个元素成为新的头,c 指向b 的下一个元素,即 9。

b -> next = NULL;

a->next = b; 使链表循环,这打破了循环,通过删除 66->9 链接。

最后返回c,所以最后的列表是:

9->14->52->87->14->17->66

【讨论】:

  • 单行代码a->next = b怎么变成循环了?我知道在a(17)的末尾连接到b(66)的头部,但代码从未将b的末尾连接到a的头部。有吗?
  • @AlexOh ab 只是指针。实际上只有一个列表。所以当a的end指向b时,和list end指向它的head是一样的。
【解决方案2】:

此代码用于将单链表旋转到右一个节点。

让我们考虑一下这个陈述

c = b->next;

声明后的指针b

struct node* b = list

指向值为66的元素

b = 66, 9, 14, 52, 87, 14, 17

因此 c 指向值为 9 的下一个元素 (b->next)。

那么在这句话之后

b -> next = NULL;

我们有

66, NULL, 9, 14, 52, 87, 14, 17
          ^
          |
          c

但是在前面的代码sn -p之后

  while(a->next != NULL) // run until a points to the last element (17) 
        a = a->next;
  a->next = b

值为 17 的最后一个模式指向之​​前值为 66 的第一个节点。

结果你有

c = 9, 14, 52, 87, 14, 17, 66, NULL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2018-01-21
    • 2020-07-15
    • 2011-04-19
    相关资源
    最近更新 更多