tGone
BAN USER#include<iostream>
using namespace std;
typedef struct node{
int data;
struct node* next;
}* Node;
Node createSLL(const int& n){
if(n <= 0)
return NULL;
Node head = (Node) malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;
Node tempHead = head;
for(int i = 2; i <= n; i++){
Node tempNode = (Node) malloc(sizeof(struct node));
tempNode->data = i;
tempNode->next = NULL;
tempHead->next = tempNode;
tempHead = tempNode;
}
return head;
}
void printSLL(Node head){
Node tempHead = head;
while(tempHead){
cout << tempHead->data << " ";
tempHead = tempHead->next;
}
cout << endl;
return;
}
bool deleteNthElement(Node& head, const int& n){
if(head == NULL || n <= 0)
return false;
Node tempHead = head;
int count = 0;
Node p, q = tempHead;
while(q != NULL && count++ < n)
q = q->next;
if(count == n+1){
p = tempHead;
while(q->next != NULL){
p = p->next;
q = q->next;
}
p->next = p->next->next;
return true;
}else if(count == n){
head = head->next;
return true;
}else{
return false;
}
}
int main(int argc, char* args[]){
Node head = createSLL(8);
printSLL(head);
if(deleteNthElement(head, 8)){
cout << "delete success..." << endl;
printSLL(head);
}else{
cout << "fail to delete node..." << endl;
}
return 0;
}
- tGone August 17, 2013
}
- tGone August 19, 2013