单链表来说,指针真的很重要,可以说对指针不熟练,很难或者不能弄懂单链表的操作,如果对指针有什么疑问的话,推荐大家学习《C和指针》这本书。
之前的代码
typedef int Datatype;
typedef struct node
{
Datatype data;
struct node* next;
}Node;
void Initlist(Node** p)
{
*p = NULL;
}
Node* buynode(Datatype data)
{
Node* p = (Node*)malloc(sizeof(struct node));
if (NULL == p)
{
return NULL;
}
p->data = data;
p->next = NULL;
return p;
}
void pushfront(Node** head, Datatype data)
{
Node* p1 = buynode(data);
if (NULL == p1)
{
return;
}
p1->next = (*head);
*head = p1;
}
void pushback(Node** head, Datatype data)
{
if (NULL == (*head))
{
*head = buynode(data);
}
else
{
Node* p = *head;
while (p->next)
{
p = p->next;
}
p->next = buynode(data);
}
}
void popback(Node** head)
{
Node* p1 = NULL;
Node* p = (*head);
if (NULL == p)
{
return;
}
while (p->next)
{
p1 = p;
p = p->next;
}
free(p);
p = NULL;
p1->next = NULL;
}
void popfront(Node** head)
{
Node* p1 = NULL;
Node* p = *head;
if (NULL == p)
{
return;
}
else
{
(*head) = (*head)->next;
free(p1);
}
}
void printlist(Node* head)
{
Node* p = head;
while (p)
{
printf("%d--->", p->data);
p = p->next;
}
printf("\n");
}
void printlistback(Node* head)
{
printlistback(head->next);
printf("%d--->", head->data);
}
void deslist(Node** head)
{
Node*p = NULL;
p = *head;
Node*newp = NULL;
while (p != NULL)
{
newp = p->next;
free(p);
p = newp;
}
*head = NULL;
}
void test()
{
Node* p = NULL;
Initlist(&p);
pushback(&p, 1);
pushback(&p, 2);
pushback(&p, 3);
pushback(&p, 4);
printlist(p);
pushfront(&p, 5);
printlist(p);
popback(&p);
printlist(p);
popfront(&p);
printlist(p);
printlistback(p);
}
int main()
{
test();
system("pause");
return 0;
}
单链表的逆序输出
void printlist(Node* head)
{
Node* p = head;
while (p)
{
printf("%d--->", p->data);
p = p->next;
}
printf("\n");
}
单链表的逆置
void reverselist(Node** head)
{
assert(head);
Node* p = *head;
Node* nextnode = NULL;
Node* nownode = NULL;
if (p == NULL || p->next == NULL)
return;
while (p)
{
nownode = p;
p = p->next;
nownode->next = nextnode;
nextnode = nownode;
}
(*head)->next = NULL;
*head = nownode;
}
查找
Node* Find(Node* head, DataType data)
{
Node* p = head;
while (p)
{
if (p->data == data)
return p;
p = p->next;
}
return NULL;
}
插入
void Insert(Node* pos, DataType data)
{
if (NULL == pos)
return;
Node* p = buynode(data);
if (NULL == p)
return;
p->next = pos->next;
pos->next = p;
}
删除
void Dele(Node** pHead, Node* pos)
{
Node* p = *pHead;
assert(pHead);
if (NULL == pHead || NULL == pos)
return;
if (*pHead == pos)
PopFront(pHead);
else
{
while (p)
{
if (p->next == pos)
break;
p = p->next;
}
p->next = pos->next;
free(pos);
}
}
节点个数
size_t Size(Node* pHead)
{
Node* p = pHead;
int count = 0;
while (p)
{
count++;
p = p->next;
}
return count;
}