交换链表中的节点 [英] Swapping nodes in a linked list

查看:64
本文介绍了交换链表中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试交换一个链表中的两个相邻节点,我想我了解如何使用一个临时节点来实现这一点的想法.

I am trying to swap two adjacent nodes in a linked list, and I think I understand the idea of how to do it using a temporary node.

这是我的结构交换函数

struct part {
   char* name;
   float price;
   int quantity;
   struct part *next;
};
typedef struct part partType;

partType *swap_node(partType **item) {

  partType *temp;
  temp = *item;
  *item = (*item)->next;
  temp->next = (*item)->next;
  (*item)->next = temp;
  return *item;
}

我想不出如何使列表中的上一个节点指向新的交换节点.我需要另一个临时变量吗?另外,我该如何考虑要交换的两个节点是列表中的前两个节点的情况.

I cant think of how to make the previous node in the list point to the new swapped node. Do i need another temp variable? Also, how do I account for the case that the two nodes to be swapped are the first two in the list.

推荐答案

从代码中看,您似乎想交换item和item-> next.

From the code, it looks like you want to swap item and item->next.

如果没有双向链表,则需要将linkPtr设置为head,然后迭代直到linkPtr-> next == * item.从那里,您可以开始在linkPtr,linkPtr-> next和linkPtr-> next-> next之间进行切换.

If you don't have a doubly-linked list, then you need to set linkPtr to head, and then iterate until linkPtr->next == *item. From there, you can start switching between linkPtr, linkPtr->next and linkPtr->next->next.

您还需要一个单独的条件,将linkPtr与head进行比较,如果是这样,则需要将head设置为新的head.

You also need a separate condition comparing linkPtr to head, and if so, then you need to set head to the new head.

这篇关于交换链表中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆