[ create a new paste ] login | about

Link: http://codepad.org/MtFUx5OY    [ raw code | output | fork ]

baojie - C++, pasted on Jun 18:
//09 Find the m-th-to-last element of a linked list
//2011-06-18

#include <iostream>
using namespace std;

struct node{
	int data;
	node* next;	
};

node *head = NULL;

void insertHead(int data){
	node *newE = new node;
	newE->data = data;	
	newE->next = head;
		
	head = newE;
}

void printList(node *pos){
	node *cursor = pos;
	while (cursor){
		cout << cursor->data << " ";
		cursor = cursor->next;
	}
}
node* mthToLast(int m){
	node *toReturn = NULL;
	node *cursor = head;
	int counter = -1;
	
	while (cursor){
		if (counter == m){
			toReturn = head;
		}
		if (toReturn) toReturn = toReturn->next;
		cursor = cursor->next;
		counter++;
	}	
	return toReturn;
}

int main(){
	for(int i=0;i<10;i++){
		insertHead(i);
	}	
	printList(head);
	node *mth = mthToLast(4);
	if (mth){	
		cout << "\nThe 4-th behind element is " << mth->data << "\n";
	}
	return 1;
}


Output:
1
2
9 8 7 6 5 4 3 2 1 0 
The 4-th behind element is 4


Create a new paste based on this one


Comments: