#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int iData;
struct Node * next;
}Node, *PNode;
void
DisplayList(PNode head);
int
AddNode(PNode *head, PNode newNode);
PNode
SearchNode(PNode head, int iKey);
int
DeleteNode(PNode *head, int iKey);
int
InsertNode(PNode head, int iOldData, int iNewData);
int main()
{
int i = 0;
PNode head = NULL;
while (i< 6)
{
PNode newNode = (PNode)malloc(sizeof(Node));
printf("Input new data:\n");
scanf("%d", &(newNode->iData));
AddNode(&head, newNode);
i++;
}
printf("Show list->\n");
DisplayList(head);
PNode pSearch = SearchNode(head, 4);
if (pSearch != NULL)
printf("Search Node->%d\n", pSearch->iData);
int ret = DeleteNode(&head, 5);
if (ret == -1)
{
printf("delete error!\n");
}
printf("Show list->\n");
DisplayList(head);
return 0;
}
int
AddNode(PNode* head, PNode newNode)
{
if (newNode == NULL) return -1;
if (*head == NULL)
{
*head = newNode;
return 0;
}
PNode tempNode = *head;
for (; tempNode->next != NULL; tempNode = tempNode->next);
tempNode->next = newNode;
return 0;
}
void
DisplayList(PNode head)
{
if (head == NULL)
{
printf ("Empty List.\n");
return;
}
PNode tempNode = head;
for (; tempNode != NULL; tempNode = tempNode->next)
{
printf("Data:%d\n", tempNode->iData);
}
}
PNode
SearchNode(PNode head, int iKey)
{
if (head == NULL) return NULL;
if (head->iData == iKey)
{
return head;
}
PNode tempNode = head;
for (; tempNode != NULL && tempNode->iData != iKey; tempNode = tempNode->next);
if (tempNode == NULL){
printf("Don't find.\n");
}
return tempNode;
}
int
DeleteNode(PNode *head, int iKey)
{
if (*head == NULL) return -1;
if ((*head)->iData == iKey)
{
PNode deleteNode = *head;
*head = (*head)->next;
free(deleteNode);
deleteNode = NULL;
return 0;
}
PNode tempNode = *head;
for (; tempNode->next != NULL; tempNode = tempNode->next)
{
if (tempNode->next->iData == iKey)
{
PNode deleteNode = tempNode->next;
tempNode->next = tempNode->next->next;
free(deleteNode);
return 0;
}
}
return -1;
}
int
InsertNode(PNode head, int iOldData, int iNewData)
{
if (head == NULL)
{
printf("Empty list!\n");
return -1;
}
PNode pNewNode = (Node*)malloc(sizeof(Node));
pNewNode->iData = iNewData;
PNode pOldNode = SearchNode(head, iOldData);
if (pOldNode == NULL)
{
return -1;
}
PNode pTempNode = pOldNode->next;
pOldNode->next = pNewNode;
pNewNode->next = pTempNode;
return 0;
}
数据结构和算法(二):单链表
最新推荐文章于 2023-06-07 21:30:16 发布