删除单链表中的倒数第n个节点的实现及测试程序

// 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;
}
 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值