用c语言写带头结点的输入单链表并逆置单链表程序
时间: 2024-10-14 13:16:49 浏览: 39
单链表逆置
在C语言中,你可以通过以下几个步骤来编写一个函数,首先创建一个链表,并插入元素,然后创建一个辅助函数来逆置链表:
1. 定义链表节点结构:
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
```
2. 创建链表头部和插入元素的函数:
```c
Node* createList(int input[], int size) {
Node* head = NULL;
Node* current = NULL;
for (int i = 0; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = input[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
return head;
}
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
```
3. 逆置链表的函数(这里采用迭代方式):
```c
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* current = head;
Node* nextTemp = NULL;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
```
4. 主函数中整合上述功能:
```c
int main() {
int input[] = {1, 2, 3, 4, 5};
int size = sizeof(input) / sizeof(input[0]);
Node* list = createList(input, size);
printf("Original List:\n");
printList(list);
list = reverseList(list);
printf("Reversed List:\n");
printList(list);
free(list); // 注意释放内存
return 0;
}
```
阅读全文