单链表
来源:互联网 发布:手机淘宝如何发布二手 编辑:程序博客网 时间:2024/06/05 03:11
Insertion
Insert a node at the head(Only 4 steps)
void push(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node;}
Insert a node at the end
/* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(struct node** head_ref, int new_data){ /* 1. allocate node */ struct node* new_node = (struct node*) malloc(sizeof(struct node)); struct node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return; }
Deletion
Delete a given key
void deleteNode(struct node **head_ref, int key){ // Store head node struct node* temp = *head_ref, *prev; // If head node itself holds the key to be deleted if (temp != NULL && temp->data == key) { *head_ref = temp->next; // Changed head free(temp); // free old head return; } // Search for the key to be deleted, keep track of the // previous node as we need to change 'prev->next' while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // If key was not present in linked list if (temp == NULL) return; // Unlink the node from linked list prev->next = temp->next; free(temp); // Free memory}
逆转链表
static void reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;}
0 0
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 5种常见排序算法的完整实现
- Redis集群管理
- Linux开发十七_yaffs文件系统
- gcc跨平台编译
- java编译与运行
- 单链表
- Linux开发十八_网卡驱动
- 文章标题
- java中==与equal的区别
- mybatis-spring整合异常SpringManagedTransaction.getTimeout()Ljava/lang/Integer
- Linux开发十九_nfs文件系统
- java编程中常见内容+++++++++++++++++++++++++++++++++++++++++++++++++++==
- STM32 最小系统 焊完之后的测试
- 循环赛日程表