[英]Data Structures - Linked list library in C
我是C的新手,所以我因為卡住而尋求幫助。 創建一個鏈表庫之后,可以從中添加,刪除和打印用戶想要的所有節點,我應該向程序中添加一個整數類型的附加函數,如果該值在其中不存在,則返回-1。鏈接列表。 如果該值確實存在於鏈表中,則它應返回元素的位置。
例如,在此鏈接列表( a -> b -> c -> d -> NULL
)中,如果我想知道c
的位置,它應該返回我一個3,如果我想知道G
的位置,它應該返回我我-1
這是我到目前為止可以制作的程序:
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
char data;
struct ListNode *nextNode;
};
typedef struct ListNode node;
int main()
{
node *startNodePtr= NULL;
int choice;
char value;
printf("\t\t\tLIST OF CHARACTERS\n");
do
{
printf("\n1.Add New Node \t2.Delete Node \t3.Print Current List \t4.QUIT\n\n");//user friendly interface
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter Character: ");
scanf("\n%c",&value);
insertNode(&startNodePtr,value);//calling the function to add a node
break;
case 2: printf("Delete Character: ");
scanf("\n%c",&value);
deleteNode(&startNodePtr,value);//calling the function to remove a node
break;
case 3: printList(startNodePtr);//calling the function to list the nodes
break;
case 4: continue;//if we type 4 it won't show the default answer
default:printf("\t\tINVALID ANSWER! Please type 1. 2. 3. or 4.\n");// in case we type any other character that is not 1, 2, 3 or 4. In this way the program will not crash
break;
}
} while(choice!=4);//keep adding or deleting nodes until we enter 4 which refers to "QUIT"
return 0;
}
void insertNode(node **sPtr, char add)//function to add a node
{
node *newPtr;
node *curPtr;
node *prevPtr;
newPtr=malloc(sizeof(node));
newPtr->data=add;
newPtr->nextNode=NULL;
prevPtr=NULL;
curPtr=*sPtr;
while(curPtr!=NULL)
{
prevPtr=curPtr;
curPtr=curPtr->nextNode;
}
if (prevPtr==NULL)
{
*sPtr=newPtr;
}
else
{
prevPtr->nextNode=newPtr;
}
}
void deleteNode(node **sPtr, char remove)//function to remove a node
{
node *curPtr;
node *prevPtr;
curPtr=*sPtr;
prevPtr=NULL;
if(curPtr->data==remove)
{
*sPtr=curPtr->nextNode;
free(curPtr);
return;
}
while (curPtr!=NULL)
{
if (curPtr->data==remove)
{prevPtr->nextNode=curPtr->nextNode;
free(curPtr);
return;}
else
{prevPtr=curPtr;
curPtr=curPtr->nextNode;}
}
}
void printList(node *sPtr)//function to list the nodes
{
if (sPtr==NULL)
{
printf("The list is empty!\n");
}
else
{
while (sPtr!=NULL)
{
printf("\n%c-->", sPtr->data);
sPtr=sPtr->nextNode;
}
} printf("NULL\n\n");
}
您已經基本解決了它,您只需要計算迭代次數,直到找到正確的元素即可。
int search(struct ListNode *node, char data) {
int position = 1;
// List is empty
if (node == NULL) {
return -1;
}
while (node != NULL) {
if (node->data == data) {
return position;
}
position++;
node = node->nextNode;
}
// Element was not in the list
return -1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.