#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
struct Node
{
int data;
struct Node *next;
}Node;
typedef struct Node list;
void InitList(list *head){
head = (list*)malloc(sizeof(list));
head->next = NULL;
}
void printList(list* head){
assert(head != NULL);
list* p = head->next;//由于头节点不保存数据,所以从下一个开始
while(p != NULL){
printf("Node data:%d\n", p->data);
p = p->next;
}
}
void creatList(list* head, int j){
list* m = NULL;
list* n = NULL;
m = head;//在此插入点
int i=0;
for(i=0; i<j; i++){
n = (list*)malloc(sizeof(list));
n->data = i;//节点赋值
m->next = n;
m=m->nex;//下一轮节点插入位置
}
m->next=NULL;//最后一个节点的下一个附空值
printf("creat list ok \n");
}
void DestroyList(list* head)
{
list*pre = head;
list*p = head->next;//清理前一个节点前,先保存后一个节点的地址
while(p != NULL)
{
free(pre);
pre = p;
p = p->next;
}//逐一释放空间
free(p);//释放最后一个
printf("destroy list ok \n");
}
//删除指定值的节点
typedef struct node {
int data;
node* next;
}node;
node *del(node* head, int num) {
node*p1, *p2;
p1 = head;
while (num != p1->data && p1->next != NULL) {
p2 = p1;//值等于num节点的前一个节点
p1 = p1->next;
}
if (num == p1->data) {//找到了
if( p1 == head){//在头部节点,或者在最尾部
head = p1->next;
}
else {//在中间节点
p2->next = p1->next;
}
free(p1);
p1 = NULL;
}
else {
cout << "can not find the node which data is num" << endl;
}
return head;
}
//从小到大顺序插入
node* insert(node* head, int num) {
node *p1, *p2;
p1 = head;
p2 = NULL;
node* s = (node*)malloc(sizeof(node));
s->data = num;
while (num > p1->data && p1->next != NULL) {
p2 = p1;//插入节点的前一个节点
p1 = p1->next;
}
if (num <= p1->data) {
if (p1 == head) {//在头部
s->next = head;
head = s;
}
//if (p1->next == NULL) {//小于p1的不可能在尾部
//}
else //介于p1 和p2中间,p2 < p1
{
p2->next = s;
s->next = p1;
}
}
else { //num >= p1->data, num最大的一个放在最后
p1->next = s;
s->next = NULL;//最后一个节点为空
}
return head;
}
node *reverse(node *head){
node *p1,*p2,*p3;
if(head == NULL ||head->next ==NULL){
return head;
}
p1 = head;
p2 = p1->next;
while(p2){
p3 = p2->next;//保存现场
p2->next = p1;//反置
p1 = p2;//后移
p2 = p3;//后移
}
head->next = NULL;//反置后最后一个节点next设置
head = p1;//指针重置
return head;
}
int main(){
int j = 10;
list*head=malloc(sizeof(list));
creatList(head, j);
if(head == NULL) return -1;
printList(head);
DestroyList(head);
return 0;
}
单链表操作
最新推荐文章于 2022-05-04 21:17:12 发布