您的位置:首页 > 其它

第五天 链表中倒数第k个结点

2016-07-27 08:39 288 查看
单链表对于我来说还是理论大于实现,趁这次机会掌握一下,包括创建,遍历以及逆序。

思路:1. 顺序下去,维持一个大小为k的矩阵,到结尾处输出矩阵第一个元素; 2. 逆序(需要两次,否则最后输出的是修改过的指针);3. 野生大神的解法,用两个指针相隔k-1距离顺序一遍搞定。

终于成功之后仍不住要吐个槽,连自相矛盾的样例都给,真是刷新了三观。

上自己的解法:

class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if (!pListHead || k <= 0)
return NULL;
else
{
vector<ListNode*> node;
int num = 1;
ListNode *p = pListHead->next;
node.push_back(pListHead);
while(p)
{
num ++;
if (node.size() == k)
node.erase(node.begin());
node.push_back(p);
p = p->next;
}
if (num < k)
return NULL;
return node[0];
}
}
};


大神解法:

public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<=0){
return null;
}
ListNode pre=head;
ListNode last=head;
for(int i=1;i<k;i++){
if(pre.next!=null){
pre=pre.next;
}else{
return null;
}
}
while(pre.next!=null){
pre = pre.next;
last=last.next;
}
return last;
}
}


自己实现的单链表功能:

#include <vector>
#include <iostream>
using namespace std;

struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :val(x), next(NULL) {}
};

ListNode* createList(int depth)
{
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
ListNode *pre = head;
int i = 0;
while(i++ < depth - 1)
{
// 这里的内存会不会泄漏
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
pre->next = p;
pre->val = i;
pre = p;
}
pre->val = depth;
pre->next = NULL;

return head;
}

void printList(ListNode *head)
{
if (!head)
cout << "NULL" << endl;
else
{
cout << head->val << "->";
ListNode *temp = head->next;
while (temp)
{
cout << temp->val << "->";
temp = temp->next;
}
cout << "NULL" << endl;
}
}

ListNode* reverseList(ListNode *head)
{
if (!head)
return NULL;
else
{
ListNode *p = head->next, *pre = head;
head->next = NULL;
while(p)
{
head = p;
p = p->next;
head->next = pre;
pre = head;
}
return head;
}
}

int main( )
{
ListNode* head = createList(5);
printList(head);
head = reverseList(head);
printList(head);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: