算法(2)—— 链表习题

题目:0:给定链表 L 和链表 P ,它们包含以升序排列的整数。操作 PrintList  ( L , P ),将打印 L 中那些由 P 所指定位置上的元素,如 P 中的元素为 1 4 5,则打印 L 中第 1,4,5个元素。

解法1: 计算记录每次 L 中遍历的步长 来打印相应节点的元素。

解法2: 循环遍历 L 并且 由整形变量记录走到第 n 个元素处,若这个 n 与 P的记录的数据相同,则打印  L 中该节点的数据。

 1 #include <stdio.h>
 2 #include "list.c"
 3 
 4 void PrintPos (List L,List P)  {
 5   Position Ppos,Lpos;
 6   Ppos = First(P);
 7   Lpos = First(L);
 8 
 9   int pre,now,step;
10   pre = 1;
11   
12   while (Lpos != NULL && Ppos !=  NULL)  {
13 
14     now = Ppos->Element;
15 
16     step = now - pre;
17     for (int i = 0; i < step ; i++)
18       Lpos = Advance (Lpos);
19 
20     printf ("%d  ",Lpos->Element);
21     pre = now;
22     Ppos = Advance(Ppos);
23   }
24 }
25 
26 
27 
28 int main()  {
29 
30     List L = MakeEmpty(NULL);
31     Position Lpos = Header(L);
32 
33     List P = MakeEmpty(NULL);
34     Position Ppos = Header(P);
35   
36     for (int i = 0;i < 10;i++)  {
37       Insert(i,L,Lpos);
38       Lpos = Advance(Lpos);
39     }
40 
41     Insert(1,P,Ppos);
42     Ppos = Advance(Ppos);
43     Insert(3,P,Ppos);
44     Ppos = Advance(Ppos);
45     Insert(9,P,Ppos);
46     
47     PrintPos(L,P);
48     
49     return 0;
50  }
solution0.c
 1 #include <stdio.h>
 2 #include "list.c"
 3 
 4 void PrintPos (List L, List P)  {
 5   Position Lpos = Header (L);
 6   Position Ppos = First (P);
 7 
 8   int vstl=0;
 9 
10   while ( Lpos != NULL && Ppos != NULL )  {
11     if  (vstl++ == Ppos->Element)  {
12 
13       if (Ppos->Element <= 0)  ;
14       else printf ("%d ",Lpos->Element);
15 
16       Ppos= Advance(Ppos);
17     }
18 
19     Lpos = Advance(Lpos);
20   }
21 }
22      
23 int main()  {
24 
25     List L = MakeEmpty(NULL);
26     Position Lpos = Header(L);
27 
28     List P = MakeEmpty(NULL);
29     Position Ppos = Header(P);
30   
31     for (int i = 0;i < 10;i++)  {
32       Insert(i,L,Lpos);
33       Lpos = Advance(Lpos);
34     }
35 
36     Insert(1,P,Ppos);
37     Ppos = Advance(Ppos);
38     Insert(3,P,Ppos);
39     Ppos = Advance(Ppos);
40     Insert(9,P,Ppos);
41     
42     PrintPos(L,P);
43     
44     return 0;
45  }
solution1.c

题目1:通过只调整指针交换单链表的的两个节点

 1 #include <stdio.h>
 2 #include "list.c"
 3 
 4 void SwapNode (List L, Position P1, Position P2)  {
 5   Position pre = FindPrevious(P1->Element,L);
 6   Position tmp = Advance(P2);
 7 
 8   pre-> Next = P2;
 9   P2 -> Next = P1;
10   P1 -> Next = tmp;
11 
12 }
13 
14 int main()  {
15 
16     List L = MakeEmpty(NULL);
17     Position Lpos = Header(L);
18 
19      
20     for (int i = 0;i < 10;i++)  {
21       Insert(i,L,Lpos);
22       Lpos = Advance(Lpos);
23     }
24 
25     PrintList(L);
26     printf("
");
27 
28     Position P1 = Find (3,L);
29     Position P2 = Advance (P1);
30     SwapNode (L,P1,P2);
31 
32     PrintList(L);
33      
34     return 0;
35  }
SwapNode.c
原文地址:https://www.cnblogs.com/hanxinle/p/7401810.html