单链表
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct Node
{
struct Node* next;
int data;
}*PNode,Node;
PNode List_Creat(PNode head)
{
PNode temp = (PNode)malloc(sizeof(Node));
if (!temp)
{
cout << "创建失败" << endl;
return NULL;
}
temp->next = NULL;
return temp;
}
int length_list(PNode pHead)
{
int i = 0;
while (pHead)
{
pHead = pHead->next;
i++;
}
return i;
}
int InsertListHead(PNode pHead, int pos, int val)
{
int i = 0;
while (i < pos - 1 && pHead != NULL)
{
i++;
pHead = pHead->next;
}
if (pHead == NULL)
{
cout << "不存在!!!" << endl;
return 0;
}
PNode temp = (PNode)malloc(sizeof(Node));
if (!temp)
{
cout << "内存分配失败,程序终止!" << endl;
return 0;
}
temp->data = val;
temp->next = pHead->next;
pHead->next = temp;
return 1;
}
void traverse(PNode head)
{
if (!head) return;
head = head->next;
while (head)
{
cout << head->data << endl;
head = head->next;
}
}
int delete_list(PNode pHead, int pos, int* val)
{
int i = 0;
while (i < pos - 1 && pHead)
{
pHead = pHead->next;
i++;
}
PNode P = pHead->next;
if (i > pos - 1 || pHead == NULL || P == NULL)
{
cout << " 不存在"<<endl;
return 0;
}
pHead->next = P->next;
*val = P->data;
free(P);
return 1;
}
int InsertList_SortHead(PNode pHead,int val)
{
return 0;
}
int main()
{
int data;
PNode head = nullptr;
head = List_Creat(head);
InsertListHead(head, 1, 1);
InsertListHead(head, 2, 2);
InsertListHead(head, 3, 3);
InsertListHead(head, 4, 4);
InsertListHead(head, 5, 5);
InsertListHead(head, 6, 9);
delete_list(head, 0, &data);
traverse( head);
return 0;
}
|