Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

c - Swapping nodes in a linked list

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.

Here is my struct swap function

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the code, it looks like you want to swap item and item->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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...