C語言實現(xiàn)輸出鏈表中倒數(shù)第k個節(jié)點
本文實例展示了C++實現(xiàn)輸出鏈表中倒數(shù)第k個節(jié)點的方法,分享給大家供大家參考之用。
運行本文所述實例可實現(xiàn)輸入一個單向鏈表,輸出該鏈表中倒數(shù)第k個節(jié)點。
具體實現(xiàn)方法如下:
/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#include <iostream>
using namespace std;
int array[] = {5, 7, 6, 9, 11, 10, 8};
const int size = sizeof array / sizeof *array;
struct Node
{
Node(int i = 0, Node *n = NULL) : item(i), next(n) {}
int item;
Node *next;
};
Node* construct(int (&array)[size])
{
Node dummy;
Node *head = &dummy;
for(int i = 0; i < size; i++) {
Node *temp = new Node(array[i]);
head->next = temp;
head = temp;
}
return dummy.next;
}
void print(Node *head)
{
while(head) {
cout << head->item << " ";
head = head->next;
}
}
Node* findKnode(Node *head, int k)
{
Node *pKnode = head;
if(head == NULL) {
cout << "link is null" << endl;
return NULL;
}
while(k--) {
if(head == NULL) {
cout << "k is bigger than the length of the link" << endl;
return NULL;
}
head = head->next;
}
while(head) {
head = head->next;
pKnode = pKnode->next;
}
return pKnode;
}
void main()
{
Node *head = construct(array);
cout << "source link: ";
print(head);
cout << endl;
Node *kNode = findKnode(head, 5);
if(kNode != NULL)
cout << "the knode is: " << kNode->item << endl;
}
測試用例如下:
1. NULL Link
head = NULL;
2. normal Link, with normal k
k <= len(head);
3. normal Link, with invalid k
k > len(head)
希望本文所述對大家C程序算法設(shè)計的學(xué)習有所幫助。
- C語言之雙向鏈表詳解及實例代碼
- C語言解字符串逆序和單向鏈表逆序問題的代碼示例
- C語言靜態(tài)鏈表和動態(tài)鏈表
- C語言創(chuàng)建和操作單鏈表數(shù)據(jù)結(jié)構(gòu)的實例教程
- C語言單鏈表的實現(xiàn)
- C語言之單鏈表的插入、刪除與查找
- C語言實現(xiàn)雙向鏈表
- C語言實現(xiàn)帶頭結(jié)點的鏈表的創(chuàng)建、查找、插入、刪除操作
- C語言實現(xiàn)單鏈表逆序與逆序輸出實例
- C語言單循環(huán)鏈表的表示與實現(xiàn)實例詳解
- c語言鏈表基本操作(帶有創(chuàng)建鏈表 刪除 打印 插入)
- C語言之單向鏈表詳解及實例代碼
相關(guān)文章
C++前綴樹字典樹的學(xué)習與模擬實現(xiàn)代碼示例
這篇文章主要介紹了C++前綴樹字典樹的學(xué)習與模擬實現(xiàn)代碼示例,Trie又被稱為前綴樹、字典樹,所以當然是一棵樹,上面這棵Trie樹包含的字符串集合是{in,inn,int,tea,ten,to},每個節(jié)點的編號是我們?yōu)榱嗣枋龇奖慵由先サ?需要的朋友可以參考下2023-07-07
對比C語言中execv相關(guān)的執(zhí)行文件的三個函數(shù)
這篇文章主要介紹了對比C語言中execv相關(guān)的執(zhí)行文件的三個函數(shù),分別為execv()函數(shù)和execve()函數(shù)以及execvp()函數(shù),需要的朋友可以參考下2015-08-08

