//定义链表的结点
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
//链表的初始化
void Init(ListNode* phead)
{
assert(phead != NULL);
if (phead == NULL)
{
return;
}
phead->m_pNext = NULL;}
//创建一个新的结点
static ListNode* BuyNode()
{
struct ListNode* pnewnode = (struct ListNode*)malloc(sizeof(struct ListNode));
assert(pnewnode != NULL);
pnewnode->m_pNext = NULL;
return pnewnode;
}
//带头节点的单链表链表的尾插
bool InsertTail(ListNode* phead, int val)
{
if (phead == NULL)
{
return false;
}
struct ListNode* pCur = phead;
while (pCur->m_pNext != NULL)
{
pCur = pCur->m_pNext;
}
struct ListNode* pnewnode = BuyNode();
pnewnode->m_nKey = val;pCur->m_pNext = pnewnode;
return true;
}
//带头节点的单链表链表的头插
bool InsertHead( ListNode* phead, int val)
{
if (phead == NULL)
{
return false;
}
struct ListNode* pnewnode = BuyNode();
pnewnode->m_nKey = val;pnewnode->m_pNext = phead->m_pNext;
phead->m_pNext = pnewnode;
return true;
}
//打印链表
void Print(ListNode* phead)
{
if (phead == NULL)
{
return;
}
struct ListNode* pCur = phead->m_pNext;
while (pCur != NULL)
{
printf("%d ", pCur->m_nKey);
pCur = pCur->m_pNext;
}
printf("\n");
}
//链表的逆置
ListNode * Merger(ListNode *head1, ListNode *head2)
{
if(head1 == NULL)
{
return head2;
}
if(head2 == NULL)
{
return head1;
}
ListNode *head = NULL;
if(head1->m_nKey <head2->m_nKey)
{
head = head1;
head->m_pNext = Merger(head1->m_pNext,head2)
}
if(head1->m_nKey > head2->m_nKey)
{
head = head2;
head->m_pNext = Merger(head1, head2->m_pNext);
}
return head;
}
//链表的第一个公共结点
ListNode* FindFirst(ListNode * ar,ListNode * br)
{
if(ar == NULL || br == NULL)
{
return NULL;
}
int alen = GetLen (ar);
int blen = GetLen (br);
int s = alen -blen;ListNode * arrlong = ar;
ListNode * arrshort = br;if(alen < blen)
{
arrlong = br;
arrshort = ar;
s = blen -alen;
}
for(int i = 0; i< s ; i++)
{
arrlong = arrlong->m_pNext;
}while(arrlong != NULL && arrshort != NULL && arrlong != arrshort)
{
arrlong = arrlong->m_pNext;
arrshort = arrshort->m_pNext;
}
ListNode * Fist ;
if(arrlong->m_pNext == arrshort->m_pNext)
Fist = arrlong ->m_pNext;
return Fist;
}
//链表的长度
int GetLen(ListNode* str)
{
if(str == NULL)
{
return -1;
}
ListNode * p=str;
int len = 0;
while(p!= NULL)
{
len ++;
str = str->m_pNext;
}
return len;
}
//从尾到头打印链表
void Reserve(ListNode* phead)
{
if(phead == NULL)
return ;
if(phead ->m_pNext != NULL)
{
Reserve(phead->m_pNext);
}
printf("%d",phead ->m_nKey);
}void Reserve(ListNode *phead)
{
if (phead == NULL)
{
return;
}
stack<ListNode *>node;
ListNode* pnode = phead;
while(pnode!=NULL)
{
node.push(pnode);
pnode = pnode->m_pNext;}
while(!node.empty())
{
pnode = node.top();
printf("%d ",pnode->m_nKey);
node.pop();
}
printf("\n");
}
链表_链表相关问题
最新推荐文章于 2022-05-05 11:41:10 发布