首页 > 代码库 > 链表中倒数第k个结点
链表中倒数第k个结点
输入一个链表,输出该链表中倒数第k个结点。
思路:使用中间变量vector去接node
class Solution {public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { ListNode*head = pListHead; vector<ListNode*>node; if(k<=0){ return NULL; } while(head!=NULL){ node.push_back(head); head=head->next; } if(k>node.size()){ return NULL; } return node[node.size()-k]; }};
思路:先求总长,总长减去倒数k,len-k,就是正着数的位置
class Solution {public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { ListNode*head = pListHead; ListNode*nodeK=pListHead; int len=0;//链表总长 int index=0;// if(k<=0){ return NULL; } while(head!=NULL){ len++; head=head->next; } if(k>len){ return NULL; } index = len-k; while(index--){ nodeK = nodeK->next; } return nodeK; }};
合并两个排序的链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { }};*/class Solution {public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) /* { ListNode *head = NULL, *node = NULL; while (pHead1 || pHead2){ if (((pHead1 == NULL) && (pHead2 != NULL)) || pHead1->val >= pHead2->val){ if (head){ node->next = pHead2; node = pHead2; } else{ node = pHead2; head = pHead2; } pHead2 = pHead2->next; } else if (((pHead2 == NULL) && (pHead1 != NULL)) || pHead1->val <= pHead2->val){ if (head){ node->next = pHead1; node = pHead1; } else{ node = pHead1; head = pHead1; } pHead1 = pHead1->next; } } node->next=NULL; return head; } */ { ListNode *head = NULL, *node = NULL; if (pHead1 == NULL) return pHead2; if (pHead2 == NULL) return pHead1; while (pHead1 && pHead2){ if ( pHead1->val >= pHead2->val){ if (head){ node->next = pHead2; node = pHead2; } else{ node = pHead2; head = pHead2; } pHead2 = pHead2->next; } else if ( pHead1->val <= pHead2->val){ if (head){ node->next = pHead1; node = pHead1; } else{ node = pHead1; head = pHead1; } pHead1 = pHead1->next; } } if (pHead1 == NULL){ node->next = pHead2; } if (pHead2 == NULL){ node->next = pHead1; } return head; }};
链表中倒数第k个结点
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。