创建一个由6个结点的单向链表,实现结点的增加、删除、查找、移动、遍历显示等功能。
时间: 2023-12-21 21:03:34 浏览: 59
好的,这是一个非常基础的数据结构操作,以下是示例代码:
定义结构体节点:
```
typedef struct Node {
int data;
struct Node* next;
} Node;
```
创建链表:
```
Node* createLinkedList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
```
增加节点:
```
void addNode(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
Node* p = head;
while(p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
```
删除节点:
```
void deleteNode(Node* head, int data) {
Node* p = head;
while(p->next != NULL && p->next->data != data) {
p = p->next;
}
if(p->next != NULL) {
Node* temp = p->next;
p->next = temp->next;
free(temp);
}
}
```
查找节点:
```
Node* findNode(Node* head, int data) {
Node* p = head->next;
while(p != NULL && p->data != data) {
p = p->next;
}
return p;
}
```
移动节点:
```
void moveNode(Node* head, int data, int move) {
Node* p = head->next;
Node* prev = head;
while(p != NULL && p->data != data) {
prev = p;
p = p->next;
}
if(p != NULL && p->next != NULL && move != 0) {
Node* next = p->next;
prev->next= next;
p->next = next->next;
next->next = p;
moveNode(head, data, move > 0 ? move - 1 : move + 1);
}
}
```
遍历显示:
```
void display(Node* head) {
Node* p = head->next;
while(p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
注意:以上代码仅为示范,实际操作中需要注意内存泄漏的问题,如有需要可以进行优化。
阅读全文