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

C语言 链表的一些操作

2008-04-30 15:41 330 查看
#include "stdafx.h"
#include "malloc.h"
struct NODE
{
char data;
struct NODE* next;
};
typedef NODE Node;
void CreateList(Node** head)
{
Node *temp,*newNode;
char ch;
(*head) = (Node*)malloc(sizeof(Node));
temp = (*head);

while(ch!='#')
{
scanf("%c",&ch);
fflush(stdin);
newNode = (Node*)malloc(sizeof(Node));
newNode->data = ch;
temp->next = newNode;
temp = newNode;
}
temp->next = NULL;//在链表输入完毕之后,最后一个元素的next要将其置为空
}
//显示链表元素
void DisplayLinklist(Node* head)
{
Node* tmp=NULL;
tmp = head->next;
while(tmp!=NULL)
{
printf("%c",tmp->data);
tmp = tmp ->next;
}
}
//插入节点
void InsertNode(Node** head,char insertData,int index)
{
Node* tmp = (*head)->next;
Node* insertNode = NULL;
int count = 0;
while(tmp!=NULL)
{
if(count == index)
{
insertNode = (Node*)malloc(sizeof(Node));
insertNode->data = insertData;
insertNode->next = tmp->next;
tmp->next = insertNode;
break;
}
else
{
tmp = tmp->next;
count++;
}
}
}
//合并有序链表
void MergeLinkList(Node** La,Node** Lb,Node** Lc)
{
Node *pa,*pb,*pc;
pa = (*La)->next;
pb = (*Lb)->next;

(*Lc) = pc = (*La);
while(pa&&pb)
{
if(pa->data <= pb->data )
{
pc->next = pa;
pc = pa;
pa=pa->next;
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa?pa:pb;
}
int main(int argc, char* argv[])
{
Node* La = NULL;
Node* Lb = NULL;
Node* Lc = (Node*)malloc(sizeof(Node));
CreateList(&La);
// InsertNode(&La,'9',3);
// DisplayLinklist(La);

CreateList(&Lb);
MergeLinkList(&La,&Lb,&Lc);
DisplayLinklist(Lc);
free(La);
free(Lb);
La = NULL;
Lb = NULL;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: