C编程中的链表的问题!
- 提问者网友:王者佥
- 2021-05-09 04:32
- 五星知识达人网友:你可爱的野爹
- 2021-05-09 05:03
遵照您的意思,我写出了如下代码
#include <stdlib.h>
#include <stdio.h>
//定义链表节点
typedef struct Node
{
char username[16];
char password[16];
Node* next;
} _NODE;
//初始化链表
void InitLink(Node* head, char* username, char* password)
{
memcpy(head->username, username, strlen(username));
memcpy(head->password, password, strlen(password));
head->next = NULL;
}
//向链表添加节点
void AddNode(Node* head, Node node)
{
Node* newnode = (Node*)malloc(sizeof(Node));
memset(newnode, 0, sizeof(Node));
memcpy(newnode, &node, sizeof(Node));
Node* temp = head;
while(temp->next)
{
temp = temp->next;
}
temp->next = newnode;
}
//释放链表
void FreeLink(Node* head)
{
Node* temp = head;
while(head->next)
{
temp = head->next;
free(head);
head = temp;
}
}
//显示链表
void ShowLink(Node* head)
{
Node* temp = head;
while(temp)
{
printf("[%s, %s]\n-->", temp->username, temp->password);
temp = temp->next;
}
printf("NULL\n");
}
//判断字符串是否相同
bool StrEqual(char* str_left, char* str_right)
{
if(strlen(str_left) != strlen(str_right))
return false;
else
{
int i=0;
while(str_left[i])
{
if(str_left[i] != str_right[i])
{
return false;
}
i ++;
}
return true;
}
}
//查找用户名和密码
bool FindUnamePsd(Node* head, char* username, char* password)
{
Node* temp = head;
while(temp)
{
if(StrEqual(username, temp->username) && StrEqual(password, temp->password))
{
return true;
}
temp = temp->next;
}
return false;
}
void main()
{
int i;
Node* head = (Node*)malloc(sizeof(Node));
memset(head, 0, sizeof(Node));
char* username = "username";
char* password = "password";
InitLink(head, username, password);
//添加5个测试节点
for(i=0; i<5; i++)
{
Node temp = {0};
temp.next = NULL;
memcpy(temp.username, username, strlen(username));
memcpy(temp.password, password, strlen(password));
temp.username[strlen(username)] = i+48;
temp.password[strlen(password)] = i+48;
AddNode(head, temp);
}
printf("Please enter two strings\n");
char username_enter[16] = {0};
char password_enter[16] = {0};
scanf("%s%s", username_enter, password_enter);
if(FindUnamePsd(head, username_enter, password_enter))
{
printf("success!\n");
}
else
{
printf("error!\n");
}
//ShowLink(head);
FreeLink(head);
}
如果有不明白的地方请追问。
谢谢采纳!