算法(2)——鏈表習題
阿新 • • 發佈:2017-08-21
給定 節點 code 定位 display 調整 urn position -c
題目: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) {solution0.c5 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 }
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("\n"); 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
算法(2)——鏈表習題