// DeleteListNode.cpp : Defines the entry point for the console application.
//删除一链表的倒数第n个节点
#include "malloc.h"
#include "stdafx.h"
#include "assert.h"
struct ListNode
{
int value;
ListNode* nextNode;
};
void createList(int *arr, int length, ListNode *front);
void deleteListNode(ListNode *front,int n);
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10]={1,2,3,4,5,6};
ListNode *front=new ListNode();
createList(arr,6,front);
deleteListNode(front,4);
while(front->nextNode!=NULL)
{
printf("%d,",front->value);
front=front->nextNode;
}
printf("%d",front->value);
getchar();
return 0;
}
//创建单链表
void createList(int *arr, int length, ListNode *front)
{
assert(arr!=NULL&&length!=0);
assert(front!=NULL);
front->value=*arr;
if(length==1)
{
front->nextNode=NULL;
}
else
{
ListNode *Node=front;
for(int i=1;i<length;i++)
{
ListNode *curNode=new ListNode();
curNode->value=*(arr+i);
Node->nextNode=curNode;
Node=curNode;
}
Node->nextNode=NULL;
}
}
//删除单链表中的倒数第n个节点
void deleteListNode(ListNode *front,int n)
{
if(front->nextNode==NULL)
{
front==NULL;
printf("delete: %d/n",front->value);
return;
}
ListNode *p1;
ListNode *p2;
p1=front;
for(int i=0;i<n-1;i++)
{
p1=p1->nextNode;
}
p2=p1;
p1=front;
ListNode *temp;
while(p2->nextNode!=NULL)
{
temp=p1;
p1=p1->nextNode;
p2=p2->nextNode;
}
printf("delete: %d/n",p1->value);
temp->nextNode=p1->nextNode;
}