bosthhe1 / -

数据结构与算法(初阶)
0 stars 0 forks source link

oj测试题 #3

Open bosthhe1 opened 2 years ago

bosthhe1 commented 2 years ago

反转链表-》1->2->3;翻转3->2->1 1,void SListRever1(Stu *s)(头插法) { Stu cur = s; Stu newnode = NULL; while (cur) { Stu next = cur->next; cur->next = newnode; newnode = cur; cur = next; } s = newnode; } 2,void SListRever(Stu *s)(断链,重造)(反转指向) { Stu p = s; Stu pp = p->next; Stu ppp = pp->next; Stu n1 = p; Stu n2 = pp; Stu n3 = ppp; n1->next = NULL; while (n2->next != NULL) { n2->next = n1; n1 = n2; n2 = n3; n3 = n3->next; } n2->next = n1; *s= n2; }

bosthhe1 commented 2 years ago

寻找倒数第k个元素(如 1,2,3,4,5,倒数第2个为 4 )(先将快指针指向前移动k-1(起始位置为0)个位置,然后slow和fast一同移动,当fast为NULL的时候,slow就为k的位置) struct LisNode FindKthToTaik(struct ListNode pListhead ,int k) { struct LisNode fast,slow;fast = slow =pListhead while(--k) {if(fast ==NULL) { return NULL;} fast = fast ->next;//向前移动k-1个位置。 } while(fast)//fast和slow同时移动,当fast为NULL的时候,slow为倒数第k个位置的值 {fast = fast ->next; slow = slow->next;} return slow; }