编程语言
首页 > 编程语言> > 算法之链表倒数第k个节点

算法之链表倒数第k个节点

作者:互联网

 

 

 分析和思路:这个需要自己创建链表

 1 #include "iostream"
 2 
 3 using namespace std;
 4 struct ListNode
 5 {
 6 
 7     int  m_nKey;
 8 
 9     ListNode* m_pNext;
10 
11 };
12 
13 
14 int main()
15 {
16     ListNode* head;
17     head = (ListNode*)malloc(sizeof(ListNode));
18     head->m_nKey = -1;
19     head->m_pNext = NULL;
20     ListNode* p = head;
21     int number = 0;
22     while (cin >> number)
23     {
24        
25         
26         while (number--)
27         {
28             int value = 0;
29             cin >> value;
30             ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
31             temp->m_nKey = value;
32             temp->m_pNext = NULL;
33             p->m_pNext= temp;
34             p = p->m_pNext;
35 
36         }
37         
38         int k = 0;
39         cin >> k;
40         if(k==0)
41         
42          {
43               cout <<0<< endl;
44             continue;
45                 //return 0;
46         }
47         ListNode* q = head->m_pNext;
48         ListNode* r = head->m_pNext;
49         for (int i = 0; i < k; i++)
50         {
51           
52             q = q->m_pNext;
53         }
54         while (q != NULL && r!= NULL)
55         {
56             q = q->m_pNext;
57             r = r->m_pNext;
58         }
59         cout << r->m_nKey << endl;
60     }
61     return 0;
62 }

 

标签:head,NULL,ListNode,int,节点,链表,nKey,倒数第,pNext
来源: https://www.cnblogs.com/technologykeeping/p/15966413.html