<pre code_snippet_id="1865241" snippet_file_name="blog_20160904_1_2613327" name="code" class="cpp"><strong><span style="font-size:18px;">往链表末尾添加结点</span></strong>
/*
注意这里pHead是一个指向指针的指针,在主函数中一般传递的是引用。
因为如果要为链表添加结点,那么就会修改链表结构,所以必须传递引用才能够保存修改后的结构。
*/
void AddToTail(ListNode** pHead,int value)
{
ListNode* pNew=new ListNode();//新插入的结点
pNew->m_nValue=value;
pNew->m_pNext=NULL;
if(*pHead==NULL)//空链表
{
*pHead=pNew;
}
else
{
ListNode* pNode=*pHead;
while(pNode->m_pNext!=NULL)
pNode=pNode->m_pNext;
pNode->m_pNext=pNew;
}
}
反转链表
ListNode* ReverseList(ListNode* pHead)
{
ListNode* pNode=pHead;//当前结点
ListNode* pPrev=NULL;//当前结点的前一个结点
while(pNode!=NULL)
{
ListNode* pNext=pNode->m_pNext;
pNode->m_pNext=pPrev;//当前结点指向前一个结点
pPrev=pNode;//pPrev和pNode往前移动。
pNode=pNext;//这里要使用前面保存下来的pNext,不能使用pNode->m_pNext
}
return pPrev;//返回反转链表头指针。
}
递归反转单链表
void reverseRec(ListNode *root, ListNode *&head)
{
if (root == NULL)
return;
if (root->next == NULL)
{
head = root;
return;
}
reverseRec(root->next, head);
root->next->next = root;
root->next = NULL;
}
链表第一个公共结点
首先遍历两个链表得到它们的长度,就能知道哪个链表比较长,以及长的链表比短的链表多几个节点。在第二次遍历的时候,先在较长的节点上走若干步,接着同时在两个链表上遍历,找到的第一个相同的节点就是它们的公共的节点。
ListNode* FindFirstCommonNode(ListNode* pHead1,ListNode *pHead2)
{
//得到两个链表的长度
unsigned int nLength1 = GetListLength(pHead1);
unsigned int nLength2 = GetListLength(pHead2);
int nLengthDif = nLength1 - nLength2;
ListNode *pHeadLong = pHead1;
ListNode *pHeadShort = pHead2;
if(nLength2 > nLength1 )
{
ListNode *pHeadLong = pHead2;
ListNode *pHeadShort = pHead1;
nLengthDif = nLength2 - nLength1;
}
//先在长链表上走几步,再同时在两个链表上遍历。
for(int i = 0;i < nLengthDif;i++)
pHeadLong = pHeadLong->m_pNext;
while((pHeadLong != NULL)&&(pHeadShort != NULL)
&&(pHeadLong != pHeadShort ))
{
pHeadLong = pHeadLong->m_pNext;
pHeadShort = pHeadShort->m_pNext;
}
//得到第一个公共节点
ListNode *pFirstCommonNode = pHeadLong ;
return pFirstCommonNode;
}
//求链表长度的函数
unsigned int GetListLength(ListNode *pHead)
{
unsigned int Length = 0;
ListNode *pNode = pHead;
while(pNode != NULL)
{
++Length;
pNode = pNode->m_pNext;
}
return Length;
}