#include <QCoreApplication>
struct ListNode
{
int m_key;
ListNode *m_next;
};
//创建一个初始值为0的链表
struct ListNode* createList()
{
struct ListNode *p_node=(ListNode*)malloc(sizeof (ListNode));
if(NULL==p_node)
{
printf("malloc error!\n");
return NULL;
}
bzero(p_node,sizeof (ListNode));
p_node->m_key=0;
p_node->m_next=NULL;
return p_node;
}
//从尾部插入
void InsertData(struct ListNode *pList,int value)
{
struct ListNode *p_node=(ListNode*)malloc(sizeof (ListNode));
p_node->m_key=value;
p_node->m_next=NULL;
//遍历直到最后一个结点
while(NULL!=pList->m_next)
{
pList=pList->m_next;
}
pList->m_next=p_node;
}
int GetListCount(struct ListNode *pList)
{
int ret_count=0;
if(NULL==pList)
{
return ret_count;
}
while(pList->m_next)
{
pList=pList->m_next;
ret_count++;
}
ret_count++;
return ret_count;
}
//反转链表,
void ReverseList(struct ListNode *pList)
{
if(NULL==pList)
{
return;
}
struct ListNode *p=pList->m_next;
//先将链表的首个和后面分开
pList->m_next=NULL;
while(p->m_next)
{
//数据是放在内村里面,指针只是取值的一种符号,指针的删除增加对数据没有改变
//把每个值插入A的第一个节点
ListNode *q = p;//取出当前q节点
p = p->m_next;//将p的pNext节点保存,这里的p已经发生了变化,q的地质发生了变化,所以后面的q->pNext不能对后面的数据进行操作
//把q的数值插入到A的pNext,而q就是当前p的值
q->m_next = pList->m_next;
pList->m_next = q;
}
}
//查找链表的中间节点
int GetListMid(struct ListNode *pList,ListNode *retNode)
{
//两个相同链表,一个每次遍历两个,一个每次遍历一个
//两倍速度遍历的链表,考虑奇偶性
struct ListNode *p=pList;
//是否是偶数,是为1,否为0,偶数返回两个中间值,奇数为一个
int isEven=0;
if(NULL==0)
{
return 0;
}
while(NULL!=p->m_next)
{
//如果为偶数个
if(NULL==p->m_next->m_next)
{
isEven=1;
p=p->m_next;
}
else
{
p=p->m_next->m_next;
pList->m_next;
}
}
retNode=pList;
}
//判断两个链表是否相交,如果相交的话,则最后一个一定相同
int IsIntersected(ListNode *pHead1,ListNode *pHead2)
{
if(NULL==pHead1||NULL==pHead2)
{
return 0;
}
while(NULL!=pHead1->m_next)
{
pHead1=pHead1->m_next;
}
while(NULL!=pHead2->m_next)
{
pHead2=pHead2->m_next;
}
if(pHead1==pHead2)
{
return 1;
}
else
{
return 0;
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ListNode *p=createList();
printf("List create Success\n");
for(int i=0;i<100;i++)
{
InsertData(p,i);
}
printf("List insert Success\n");
// delete_node(p,5);
// reversw_list(p);
//获得链表长度
int listCount=GetListCount(p);
printf("List count is %d.\n",listCount);
ReverseList(p);
ListNode *ret=NULL;
int isEven=GetListMid(p,ret);
printf("----begin----\n");
while(NULL!=p->m_next)
{
printf("p_data is %d.\n",p->m_key);
p=p->m_next;
}
printf("p_data is %d.\n",p->m_key);
printf("----end----\n");
return 0;
}
C语言写的一些链表算法
最新推荐文章于 2023-03-23 20:32:10 发布