#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
// 创建新节点
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 遍历并修改链表
void traverseAndModify(struct Node *head) {
struct Node* current = head;
while (current != NULL && current->next != NULL) {
current->data = current->data + current->next->data;
current = current->next;
}
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
// 创建链表 1 -> 2 -> 3 -> 4
struct Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
printf("Original List: ");
printList(head);
traverseAndModify(head);
printf("Modified List: ");
printList(head);
// 释放链表内存
struct Node* current = head;
struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
return 0;
}