用c语言写单链条交换元素并展示链条
时间: 2024-05-16 13:12:03 浏览: 11
可以的,以下是用C语言编写的单链表交换元素并展示链表的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void swapNode(struct Node *node1, struct Node *node2) {
int temp = node1->data;
node1->data = node2->data;
node2->data = temp;
}
void displayList(struct Node *head) {
struct Node *current = head;
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
int main() {
struct Node *head = NULL;
struct Node *second = NULL;
struct Node *third = NULL;
// allocate memory for the nodes
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
// assign values to the nodes
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// original list
printf("Original List: ");
displayList(head);
// swap second and third nodes
swapNode(second, third);
// modified list
printf("\nModified List: ");
displayList(head);
return 0;
}
```
以上代码是创建了一个包含三个节点的单链表,并使用了`swapNode`函数交换了第二个和第三个节点的数据,最后使用`displayList`函数展示了整个链表。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)