Created
February 25, 2013 13:23
-
-
Save ThunderXu/5029766 to your computer and use it in GitHub Desktop.
Implement an algorithm to find the kth to last element of a singly linked list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
class Node | |
{ | |
public: | |
int data; | |
Node* next; | |
}; | |
void Input(Node*, Node*); | |
void Outputkth(Node*, Node*,int); | |
void Del(Node*, Node*); | |
int main() | |
{ | |
Node *head = new Node(); | |
Node *end = new Node(); | |
Input(head,end); | |
std::cout<<"Enter k please:"<<std::endl; | |
int k; | |
std::cin>>k; | |
Outputkth(head,end,k); | |
Del(head,end); | |
return 0; | |
} | |
//input the linked list | |
void Input(Node* head, Node* end) | |
{ | |
using namespace std; | |
int num; | |
Node *current = head; | |
while(cin>>num) | |
{ | |
current->next = new Node(); | |
current = current->next; | |
current->data = num; | |
} | |
current->next = end; | |
cin.clear(); | |
} | |
void Outputkth(Node* head, Node* end,int k) | |
{ | |
using namespace std; | |
Node *current = head; | |
Node *kth = head; | |
for(int i=0;i<k;i++) | |
{ | |
kth=kth->next; | |
} | |
while(kth!=end) | |
{ | |
current = current->next; | |
kth = kth->next; | |
} | |
while(current!=end) | |
{ | |
cout<<current->data<<" "; | |
current = current->next; | |
} | |
cout<<endl; | |
} | |
void Del(Node* head, Node* end) | |
{ | |
Node *current = head; | |
while(current->next!=end) | |
{ | |
Node* former = current; | |
current = current->next; | |
former->next = current->next; | |
delete current; | |
current = former; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment