- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- // 练习单链表操作: 给出单链表 head 和 n, 要求删除单链表倒数第 n 个结点, 并连接剩余结点
- // 例子: 1-2-3-4-5,n=2, 删除后应该是: 1-2-3-5
- typedef struct ListNode{
- int data;
- ListNode *next;
- }ListNode;
- int createList(ListNode *&head,int a[],int len)
- {
- head=(ListNode*)malloc(sizeof(ListNode));
- head->next=NULL;
- ListNode *p,*q;
- q=head;
- for(int i=0;i<len;i++)
- {
- p=(ListNode*)malloc(sizeof(ListNode));
- p->data=a[i];
- p->next=NULL;
- q->next=p;
- q=q->next;
- }
- }
- void print(ListNode *p)
- {
- p=p->next;
- while(p)
- {
- printf("%d\n", p->data);
- p=p->next;
- }
- }
- void f(ListNode*head,int n)
- {
- ListNode *p,*q;
- p=q=head->next;// 头节点不存储数据, 从头结点的下一个开始
- int cnt=0;
- while(cnt<n)
- {
- p=p->next;
- cnt++;
- }
- while(p->next)// 继续往下走
- {
- p=p->next;
- q=q->next;
- }
- q->next=q->next->next;
- }
- int main(int argc, char const *argv[])
- {
- int a[]={1,2,3,4,5};
- ListNode *head;
- int len=sizeof(a)/sizeof(int);
- createList(head,a,len);
- print(head);// 单链表建立后打印它
- f(head,2);// 删除倒数第二个结点
- printf("\n");
- print(head);// 打印处理后的单链表
- return 0;
- }
运行结果:
来源: http://www.bubuko.com/infodetail-3285322.html