前提
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
typedef struct Node node;
void printList(struct Node* n)
{
while(n != NULL) {
printf(" %d ", n->data);
n = n->next;
}
puts("");
}
void appendToArray(node** head_ref, int* a, int len)
{
if (len <= 0) {
printf("the given len must be greater than or equal to 0");
return ;
}
if (*head_ref != NULL) {
printf("please input a linked list for empty");
return ;
}
node* temp = (node*)malloc(sizeof(node));
*head_ref = temp;
temp->data = a[0];
temp->next = NULL;
for(int i=1; i<len; ++i) {
node *new_node = (node*)malloc(sizeof(node));
new_node->data = a[i];
new_node->next = NULL;
temp->next = new_node;
temp = new_node;
}
}
单链表反转
void reverselinkedlist(node** head_ref)
{
node* pre = null;
node* current = *head_ref;
node* next = current->next;
while(current != null) {
next = current->next;
current->next = pre;
pre = current;
current = next;
}
*head_ref = pre;
}
int main()
{
node* head = NULL;
int a[5] = {1, 2, 3, 4, 5};
appendToArray(&head, a, 5);
printList(head);
reverseLinkedList(&head);
printList(head);
}
链表中环的检测
两个有序的链表合并
递归的写法更好