我想在headnode或其他節點後面添加newnode,但節點不添加whay我應該怎麼做?C鏈表列表節點不添加
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node *head, *tail, *behind, *prev,*twonext;
Node *new_node(int val){
struct node *ptr = malloc(sizeof(*ptr));
if(ptr==NULL){
perror("malloc:");
printf("\nFailed to create a new node.\n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
return ptr;
}
Node *creatFirstNode(int val){
return head = tail = new_node(val);
}
void printList(void){
Node *np = head;
printf("\n----Value in Liked list----\n");
while(np){
printf("[%d], ", np->val);
np = np->next;
}
// printf("NULL\n");
}
void freeList(void){
while(head){
Node *np = head->next;
free(head);
head = np;
}
tail = NULL;
}
int main(void){
char cmd =' ';
int k;
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do {
int v = 0;
int s = 0;
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value or 'p'rint or 'q'uit:");
scanf(" %c", &cmd);
fflush(stdin);
switch(cmd){
add headnode ----------------------------------------- ---------------------------
case 'h':
printf("Enter value node head:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
Node *np = new_node(v);
np->next = head;
head = np;
}
fflush(stdin);
printList();
break;
add tail node ------------- -------------------------------------------------- -----
case 't':
printf("Enter value node tail:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
tail = tail->next = new_node(v);
}
fflush(stdin);
printList();
break;
加在節點後面我在這裏有問題我應該怎麼做? -----------------------------------------------
case 'b':
printf("Enter node value:");
scanf("%d",&v);
Node *np = new_node(v);
printf("Adding value [%d] in new node:",v);
// behind = behind->next = new_node(v);
if(head == NULL)
{
printf("No node to insert behind:");
}
else
{
printf("\nAdd new node behind the value:");
scanf("%d", &s);
np = head;
while(np->val != s);
{
prev=np;
np =np->next;
}
twonext=np->next;
np->next=NULL;
np->next=twonext;
}
fflush(stdin);
printList();
break;
/*case 'p':
printList();
break;
*/
case 'q':
freeList();
printf("\nBye!\n");
getch();
break;
default:
printf("\n Invalid Input ");
}
}while(cmd != 'q');
return 0;
}
你使用過'gdb'嗎?跟蹤內存地址。 –
當您鍵入一個數字並點擊'enter'時,換行符可能會出現問題。 –
@Nguaial我應該如何解決這個問題兄弟你能告訴我嗎? – Crystals