我是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");
}
答案 0 :(得分:0)
你已经基本解决了它,你只需要计算迭代次数,直到找到正确的元素。
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;
}