输入一个链表,输出该链表中倒数第k个结点
示例:
输入
3
1 2 3
1
8
1 2 3 4 5 6 7 8
4
输出
3
5
#include <stdlib.h>
#include <stdio.h>
typedef struct ListNode
{
int val;
struct ListNode* m_pNext;
}ListNode;
ListNode* BuyNote(int x)
{
ListNode* ret = (ListNode*)malloc(sizeof(ListNode));
ret->val = x;
ret->m_pNext = NULL;
return ret;
}
int main()
{
int n = 0;
int tmp = 0;
int k = 0;
ListNode* head = NULL;
ListNode* cur = NULL;
int i = 2;
while (i--)
{
scanf("%d", &n);
int m = n;
while (m--)
{
scanf("%d", &tmp);
ListNode* ptmp = BuyNote(tmp);
if (head == NULL)
{
head = ptmp;
cur = head;
}
else
{
cur->m_pNext = ptmp;
cur = cur->m_pNext;
}
}
scanf("%d", &k);
n = n - k;
cur = head;
while (n--)
{
cur = cur->m_pNext;
}
printf("%d \n", cur->val);
while (head)
{
cur = head;
head = head->m_pNext;
free(cur);
}
}
return 0;
}
输入
3
1 2 3
1
8
1 2 3 4 5 6 7 8
4
输出
3
5
#include <stdlib.h>
#include <stdio.h>
typedef struct ListNode
{
int val;
struct ListNode* m_pNext;
}ListNode;
ListNode* BuyNote(int x)
{
ListNode* ret = (ListNode*)malloc(sizeof(ListNode));
ret->val = x;
ret->m_pNext = NULL;
return ret;
}
int main()
{
int n = 0;
int tmp = 0;
int k = 0;
ListNode* head = NULL;
ListNode* cur = NULL;
int i = 2;
while (i--)
{
scanf("%d", &n);
int m = n;
while (m--)
{
scanf("%d", &tmp);
ListNode* ptmp = BuyNote(tmp);
if (head == NULL)
{
head = ptmp;
cur = head;
}
else
{
cur->m_pNext = ptmp;
cur = cur->m_pNext;
}
}
scanf("%d", &k);
n = n - k;
cur = head;
while (n--)
{
cur = cur->m_pNext;
}
printf("%d \n", cur->val);
while (head)
{
cur = head;
head = head->m_pNext;
free(cur);
}
}
return 0;
}
全部评论
相关推荐
06-20 18:26
成都理工大学 测试工程师 点赞 评论 收藏
分享
06-21 13:04
东北大学 C++ 点赞 评论 收藏
分享
点赞 评论 收藏
分享