单链表按值操作

#include 
using namespace std;
typedef struct Node
{
	int val;
	Node *next;
}node;
node* mycreat(int n)
{
	node *head=NULL,*p=NULL,*sec=NULL;
	head=(node*)malloc(sizeof(node));
	p=head;
	while (n--)
	{
		int v;
		scanf("%d",&v);
		sec=(node*)malloc(sizeof(node));
		sec->val=v;
		p->next=sec;
		p=sec;
	}
	p->next=NULL;
	return head;
}
node* mydel(node *head,int m)
{
	node *p=NULL,*q=NULL,*s=NULL;
	q=head;
	p=head->next;
	while(p!=NULL)
	{
		if (p->val==m)
		{
			if(p->next==NULL) 
			{
				q->next=NULL;
				break;
			}
			else
			{
				q->next=p->next;
			delete p;
		
			break;
			}
		}
		else if(p->val>m)
		{
			s=(node*)malloc(sizeof(node));
            s->val=m;
			s->next=p;
			q->next=s;
			break;
		}
		else if(p->valnext==NULL)
		{
			s=(node*)malloc(sizeof(node));
            s->val=m;
			s->next=NULL;
			p->next=s;
			break;
		}
		else
		{
			p=p->next;
			q=q->next;
		}
	}
	return head;
}
void myprint(node *head)
{
	if (head->next==NULL)
	{
		return;
	}
	int f=0;
	node *p=NULL;
	p=head->next;
	while(p!=NULL)
	{
		if(f==0) 
			printf("%d",p->val);
		else
			printf(" %d",p->val);
		f++;
		p=p->next;
	}
	printf("\n");
	return ;
}
int main()
{
	int n,m;
	node *head=NULL,*dhead=NULL;
	while(~scanf("%d",&n))
	{
		if (n!=0)
		{
		head=mycreat(n);
		scanf("%d",&m);
		dhead=mydel(head,m);
		myprint(dhead);	
		}
		else
		{
			scanf("%d",&m);
			printf("%d\n",m);
		}

	}
	return 0;
}

你可能感兴趣的:(数据结构,单链表)