您的位置:首页 > 编程语言 > C语言/C++

c语言单链表的各种操作<未完>

2013-01-04 16:06 417 查看
#include<stdio.h>
#include<stdbool.h>

struct Node
{
int val;
Node* next;
};

Node* Create()
{
bool bFlag=true;
Node *pHead=NULL;
Node *pCur=NULL;
Node* pTemp=NULL;
int nVal;
pHead=(Node*)malloc(sizeof(Node));
if(NULL==pHead)
{
return NULL;
}
pHead->next=NULL;
pCur=head;

while(bFlag)
{
pTemp=(Node*)malloc(sizeof(Node));
printf("please input node value,if the value is 0 input finished.");

scanf("%d",&nVal);
if(nVal!=0)
{
pTemp->val=nVal;
pTemp->next=NULL;

pCur->next=pTemp;
pCur=pTemp;
}
else
{
bFlag=false;
}
}

pHead=pHead->next;
pCur->next=NULL;

return pHead;
}

int length(Node* head)
{
if(head==NULL)
{
return 0;
}

int i=0;
Node* cur=head;
while(cur!=NULL)
{
i++;
cur=cur->next;
}

return i;
}

bool print(Node *head)
{
if(NULL==head)
{
return false;
}

printf("list info:");
Node *cur=head;
while(NULL!=cur)
{
printf("%d\n",cur->val);
cur=cur->next;
}
return true;
}

Node* del(Node* head, int pos)
{
if((head==NULL)||(pos<1)||(pos>length(head)))
{
return NULL;
}

Node* cur=head;
if(pos==1)
{
cur=cur->next;
free(head);
head=NULL;
return cur;
}

//定位到删除节点的前一个节点
int i=0;
for(i=0;i<pos-1;i++)
{
cur=cur->next;
}

cur->next=cur->next->next;

return head;
}

Node* addafterpos(Node *head, int pos, int val)
{
if((head==NULL)||(pos<1)||(pos>length(head)))
{
return NULL;
}

Node* newnode=(Node*)malloc(sizeof(Node));
if(newnode==NULL)
{
return NULL;
}
newnode->val=val;
newnode->next=NULL;

Node* cur=head;
if (pos==length(head))
{
while(cur->next!=NULL)
{
cur=cur->next;
}
cur->next=newnode;
}

int i=0;
for(i=0;i<pos;i++)
{
cur=cur->next;
}

newnode=cur->next;
cur->next=newnode;

return head;
}

Node* insertbefore(Node* head, int pos, int val)
{
if((head==NULL)||(pos<1)||(pos>length(head)))
{
return NULL;
}

Node* newnode=(Node*)malloc(sizeof(Node));
if(newnode==NULL)
{
return NULL;
}
newnode->val=val;
newnode->next=NULL;
Node* cur=head;
if(pos==1)
{
newnode->next=cur;
return newnode;
}

int i=0;
for(i=0;i<pos-1;i++)
{
cur=cur->next;
}

newnode->next=cur->next;
cur->next=newnode;

return head;
}

int main()
{
Node *head;
int len;
head=Create();
len=length(head);
printf("len:%d", len);

print(head);
head=del(head,1);
print(head);

head=addafterpos(head,4,5);
print(head);

head=insertbefore(head,1,1);
print(head);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: