1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 //练习单链表操作:给出单链表 head 和 n,要求删除单链表倒数第n个结点,并连接剩余结点
5 //例子:1-2-3-4-5,n=2,删除后应该是:1-2-3-5
6 typedef struct ListNode{
7 int data;
8 ListNode *next;
9 }ListNode;
10
11 int createList(ListNode *&head,int a[],int len)
12 {
13 head=(ListNode*)malloc(sizeof(ListNode));
14 head->next=NULL;
15 ListNode *p,*q;
16 q=head;
17 for(int i=0;i<len;i++)
18 {
19 p=(ListNode*)malloc(sizeof(ListNode));
20 p->data=a[i];
21 p->next=NULL;
22 q->next=p;
23 q=q->next;
24 }
25
26 }
27 void print(ListNode *p)
28 {
29 p=p->next;
30 while(p)
31 {
32 printf("%d
", p->data);
33 p=p->next;
34 }
35 }
36 void f(ListNode*head,int n)
37 {
38 ListNode *p,*q;
39 p=q=head->next;//头节点不存储数据,从头结点的下一个开始
40 int cnt=0;
41 while(cnt<n)
42 {
43 p=p->next;
44 cnt++;
45 }
46 while(p->next)//继续往下走
47 {
48 p=p->next;
49 q=q->next;
50 }
51 q->next=q->next->next;
52 }
53 int main(int argc, char const *argv[])
54 {
55 int a[]={1,2,3,4,5};
56 ListNode *head;
57 int len=sizeof(a)/sizeof(int);
58 createList(head,a,len);
59 print(head);//单链表建立后打印它
60 f(head,2);//删除倒数第二个结点
61 printf("
");
62 print(head);//打印处理后的单链表
63 return 0;
64 }
运行结果: