編程演算法 - 兩個鏈表的第一個公用結點 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   兩個鏈表的第一個公用結點   代碼   c   

兩個鏈表的第一個公用結點 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


題目: 輸入兩個鏈表, 找出它們的第一個公用結點.


計算鏈表的長度, 然後移動較長鏈表的指標, 使其到相同結點的距離的相同, 再同時移動兩個鏈表的指標, 找到相同元素.

時間複雜度: O(n)


代碼:

/* * main.cpp * *  Created on: 2014.6.12 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>#include <string.h>struct ListNode {int m_nKey;ListNode* m_pNext;};size_t GetListLength (ListNode* pHead) {size_t nLength = 0;ListNode* pNode = pHead;while (pNode != NULL) {++nLength;pNode = pNode->m_pNext;}return nLength;}ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {size_t nLength1 = GetListLength(pHead1);size_t nLength2 = GetListLength(pHead2);int nLengthDif = nLength1 - nLength2;ListNode* pListHeadLong = pHead1;ListNode* pListHeadShort = pHead2;if (nLength2 > nLength1) {pListHeadLong = pHead2;pListHeadShort = pHead1;nLengthDif = nLength2 - nLength1;}for (int i=0; i<nLengthDif; ++i)pListHeadLong = pListHeadLong->m_pNext;while ((pListHeadLong != NULL) && (pListHeadShort != NULL)&& (pListHeadLong != pListHeadShort)) {pListHeadLong = pListHeadLong->m_pNext;pListHeadShort = pListHeadShort->m_pNext;}ListNode* pFirstCommonNode = pListHeadLong;return pFirstCommonNode;}int main(void){ListNode* pHead1 = new ListNode();ListNode* pHead1Node1 = new ListNode();ListNode* pHead1Node2 = new ListNode();ListNode* pHead1Node3 = new ListNode();ListNode* pHead1Node4 = new ListNode();pHead1->m_nKey = 1;pHead1Node1->m_nKey = 2;pHead1Node2->m_nKey = 3;pHead1Node3->m_nKey = 6;pHead1Node4->m_nKey = 7;pHead1->m_pNext = pHead1Node1;pHead1Node1->m_pNext = pHead1Node2;pHead1Node2->m_pNext = pHead1Node3;pHead1Node3->m_pNext = pHead1Node4;pHead1Node4->m_pNext = NULL;ListNode* pHead2 = new ListNode();ListNode* pHead2Node1 = new ListNode();pHead2->m_nKey = 4;pHead2Node1->m_nKey = 5;pHead2->m_pNext = pHead2Node1;pHead2Node1->m_pNext = pHead1Node3;ListNode* result = FindFirstCommonNode(pHead1, pHead2);printf("result = %d\n", result->m_nKey);    return 0;}

輸出:

result = 6







相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.