今日学习了,单链表的基本操作:
定义:
typedef struct ListNode { int data; struct ListNode *next; } ListNode;
初始化:
void insertAtHead(ListNode **head, int value) { ListNode *newNode = (ListNode *)malloc(sizeof(ListNode)); newNode->data = value; newNode->next = *head; *head = newNode; }
插入:
头插法:
void insertAtHead(ListNode **head, int value) { ListNode *newNode = (ListNode *)malloc(sizeof(ListNode)); newNode->data = value; newNode->next = *head; *head = newNode; }
尾插法:
void insertAtTail(ListNode **head, int value) { ListNode *newNode = (ListNode *)malloc(sizeof(ListNode)); newNode->data = value; newNode->next = NULL; if (*head == NULL) { *head = newNode; return; } ListNode *current = *head; while (current->next!= NULL) { current = current->next; } current->next = newNode; }
删除:
void deleteAtHead(ListNode **head) { if (*head == NULL) { return; // 空链表,无需删除 } ListNode *temp = *head; *head = (*head)->next; free(temp); }
查找:
按值查找:
void deleteAtHead(ListNode **head) { if (*head == NULL) { return; // 空链表,无需删除 } ListNode *temp = *head; *head = (*head)->next; free(temp); }
按索引查找:
ListNode* searchByIndex(ListNode *head, int index) { int count = 0; ListNode *current = head; while (current!= NULL && count < index) { current = current->next; count++; } if (count == index && current!= NULL) { return current; // 找到指定索引位置的节点,返回其指针 } return NULL; // 索引超出范围或链表为空,返回 NULL }