关于链表操作的问题

来源:互联网 发布:直通车软件哪个好 编辑:程序博客网 时间:2024/06/03 21:29

【题目】输入一个链表,输出该链表中倒数第k个结点。

<pre name="code" class="cpp">#include<iostream>#include<iomanip>#include <stdio.h>#include <string.h>#include <list>#include <vector>#include <cstdio>#include <stack>#include <queue>#include <sstream>#include <stdlib.h>#include<algorithm>using namespace std;struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}//成员中有指针,一定要重载构造函数ListNode(){}//保留默认构造函数};//使用思路是,两个指针,让第一个指针先走K-1步,则当第一个指针走到链表尾时,第二个指针在倒数K的位置上ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {if (pListHead == NULL)//注意判断头结点是否为空return NULL;int len = 0;ListNode * psecond = pListHead;if (k == 0)//注意K是否为0{return NULL;}else{for (unsigned int i = 1; i < k; ++i)//注意这里是从1开始计算{if (pListHead->next != NULL)pListHead = pListHead->next;else//特殊处理K比节点数量大的情况,直接返回空{// if the number of nodes in the list is less than k, // do nothingreturn NULL;}}while (pListHead->next != NULL){pListHead = pListHead->next;psecond = psecond->next;}return psecond;}}//创建一个链表结点ListNode* CreateListNode(int value){ListNode *pNode = new ListNode();pNode->val = value;pNode->next = NULL;return pNode;}//往链表末尾添加结点/*注意这里pHead是一个指向指针的指针,在主函数中一般传递的是引用。因为如果要为链表添加结点,那么就会修改链表结构,所以必须传递引用才能够保存修改后的结构。*/void AddToTail(ListNode** pHead, int value){ListNode* pNew = new ListNode();//新插入的结点pNew->val = value;pNew->next = NULL;if (*pHead == NULL)//空链表{*pHead = pNew;}else{ListNode* pNode = *pHead;while (pNode->next != NULL)pNode = pNode->next;pNode->next = pNew;}}//遍历链表中的所有结点void PrintList(ListNode* pHead){ListNode *pNode = pHead;while (pNode != NULL){cout << pNode->val << " ";pNode = pNode->next;}cout << endl;}void main(){//创建结点ListNode* pNode1 = CreateListNode(1);//创建一个结点//往链表中添加新结点AddToTail(&pNode1, 2);AddToTail(&pNode1, 3);AddToTail(&pNode1, 4);AddToTail(&pNode1, 5);AddToTail(&pNode1, 6);AddToTail(&pNode1, 7);PrintList(pNode1);//打印//反转链表ListNode* KthNode = FindKthToTail(pNode1,0);PrintList(KthNode);system("pause");}

【参考】http://zhedahht.blog.163.com/blog/static/2541117420072114478828/
http://www.cnblogs.com/xwdreamer/archive/2012/04/27/2473355.html

0 0
原创粉丝点击