我想在头节点或其他节点后面添加新节点,但节点不添加 whay 我应该怎么做吗?
#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("NULLn");
}
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 -----------nn");
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){
添加头节点--------------------------------------------------------------------
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;
添加尾节点--------------------------------------------------------------------
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;
}
如果你想在其他节点之间放置一个新节点,你必须将上一个节点链接到下一个节点>下一个节点,将新节点>下一个节点链接起来。仅此而已,下面是一个代码示例。
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);
Node *tmp = head; /*You need a tmp variable to go through the list*/
while(tmp->val != s && tmp != NULL);
{
prev=tmp; /*Save the prev node*/
tmp =tmp->next; /*Go through*/
}
if(tmp != NULL){
prev->next = np; /*Link the prev with the new*/
np->next = tmp; /*Link the new one with the subsequent*/
}
}
fflush(stdin);
printList();
break;