[Classic Interview Questions] solving the difference set between Set A and B
[Question]
It is known that elements of set A and Set B are stored in A single-chain table without header nodes. The function difference () is used to solve the difference set between set A and Set B, and save the result in the single-chain table of set.
For example, if A = {5, 10, 20, 15, 25, 30} is set, B = {5, 15, 35, 25} is set, and A = {10, 20, 30} is calculated }.
Struct:
struct ListNode{ int val; ListNode *next;};
Complete the void difference function (ListNode ** LA, ListNode * LB)
Code 1]
# Include
# Include
# Include using namespace std; struct ListNode {int val; ListNode * next;}; // output set void Display (ListNode * root) {ListNode * p = root; while (p) {cout <
Val <
Next; }}// find that the Difference set of the Two sets is saved in void Difference (ListNode ** LA, ListNode * LB) in LA) {// fault tolerance Processing if (* LA = NULL | LB = NULL) {return;} ListNode * pa, * pb, * pre, * node; pa = * LA; pre = NULL; bool isDelete; // traverse LA while (pa) {pb = LB; isDelete = false; while (pb) {// Delete pa if (pa-> val = pb-> val) {isDelete = true; // Header element if (pre = NULL) {* LA = pa-> next; pa = * LA;} // if else {node = pa; pre-> next = pa-> next; delete node; pa = Pre-> next;} break;} // if pb = pb-> next;} // while // if a deleted pa is found, jump to pa-> next if (! IsDelete) {pre = pa; pa = pa-> next; }}// while} int main () {int arrayA [] = {5, 10, 20, 15, 25, 30 }; int arrayB [] = {5, 15, 35, 25}; ListNode * node; // set A ListNode * LA = (ListNode *) malloc (sizeof (ListNode )); LA-> val = 5; LA-> next = NULL; ListNode * p = LA; for (int I = 1; I <6; I ++) {node = (ListNode *) malloc (sizeof (ListNode); node-> val = arrayA [I]; node-> next = NULL; p-> next = node; p = node;} // Set B ListNode * LB = (ListNode *) malloc (sizeof (ListNode); LB-> val = 5; LB-> next = NULL; p = LB; for (int I = 1; I <4; I ++) {node = (ListNode *) malloc (sizeof (ListNode )); node-> val = arrayB [I]; node-> next = NULL; p-> next = node; p = node;} // calculate the Difference (& LA, LB); // output the AB difference set Display (LA );}
Code 2]
// Calculate that the Difference set of the Two sets is saved in void Difference (ListNode ** LA, ListNode * LB) of LA) {// fault tolerance Processing if (* LA = NULL | LB = NULL) {return;} ListNode * pa, * pb, * pre, * node; pa = * LA; pre = NULL; // traverse LA while (pa) {pb = LB; // traverse until the end while (pb! = NULL & pa-> val! = Pb-> val) {pb = pb-> next;} // while // pb does not have the same element as if (pb = NULL) {pre = pa; pa = pa-> next;} // the same element else {// Header element if (pre = NULL) {* LA = pa-> next; pa = pa-> next;} else {node = pa; pre-> next = pa-> next; pa = pa-> next; delete node ;} // if} // while}