问题
I am trying to program a text editor in C. I am having trouble with inserting an element in a linked list. The program simply won't insert anything in the middle of the linked list.
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
I used singly linked list.
struct node {
struct node *previous;
int c;
int x;
int y;
struct node *next;
}*head;
this works fine:
void characters(int typed, int xpos, int ypos) //assign values of a node
{
struct node *temp,*var,*temp2;
temp=(struct node *)malloc(sizeof(struct node));
temp->c=typed;
temp->x=xpos;
temp->y=ypos;
if(head==NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp2=head;
while(temp2!=NULL)
{
var=temp2;
temp2=temp2->next;
}
temp2=temp;
var->next=temp2;
temp2->next=NULL;
}
}
this works just fine too.
void printer() //to print everything
{
struct node *temp;
temp=head;
while(temp!=NULL)
{
gotoxy(temp->x,temp->y);
printf("%c",temp->c);
temp=temp->next;
}
}
this works just fine too:
void deletesEnd //delete at the end
{
struct node *temp,*last;
temp=head;
last=temp;
while(temp!=NULL && temp->next!=NULL)
{
last=temp;
temp=temp->next;
}
if(last==temp)
{
free(temp);
head=NULL;
}
else{
free(last->next);
last->next=NULL;
}
}
THIS IS THE PROBLEM:
void checker(int ch, int xpos, int ypos)
{
int flag=0;
struct node *temp,*temp1,*insert_node;
temp=head;
while(temp!=NULL)
{
if(temp->x==xpos && temp->y==ypos)
{
temp1=temp;
temp=insert_node;
insert_node->c=ch;
insert_node->x=xpos;
insert_node->y=ypos;
insert_node->next=temp1;
flag=1;
break;
}
else
temp= temp->next;
}
free(temp);
free(temp1);
if(flag==0)
characters(ch,xpos,ypos);
}
main()
{
int c; //for storing the character
int x,y; //for the position of the character
clrscr();
for(;;)
{
c=getch();
x=wherex();
y=wherey();
if(c==27)
exit(0);
else if(c==0|| c==224)
{
switch(getch())
{
case 72: //for up
gotoxy(x,y-1);
break;
case 80: //for down
gotoxy(x,y+1);
break;
case 75: //for left
gotoxy(x-1,y);
break;
case 77: //for right
gotoxy(x+1,y);
break;
}
}
else if(c==13)
{
printf("\n");
}
else if(c==8) //for backspace
{
deletesEnd();
clrscr();
printer();
}
else //for normal characters
{
checker(c,x,y);
// characters(c,x,y);
printer();
}
}
}
I tried to debug it, it goes inside the loop with the conditional statement of ((temp->x==xpos && temp->y==ypos)) Thus, the program is supposed to insert an element but it doesn't. :(
回答1:
Maybe you have to malloc a struct node for the element you want to insert first, not just declare a struct node *.
Try to add struct node *insert_node = (struct node *)malloc(struct node) in your checker method.
回答2:
Try concept of insertion from this one - It can insert a node from front end
Just make a new pointer to node and name it create
struct node *create;
int item;
printf("Enter a number you want to insert\n\t");
scanf("%d",&item);
create = (struct node*)malloc(sizeof(struct node*));
create->info = item;
create->ptr = first;
HEAD = create;
来源:https://stackoverflow.com/questions/18042984/insert-in-linked-list-turbo-c