刷题总结1

来源:互联网 发布:什么软件替代迅雷 编辑:程序博客网 时间:2024/05/17 03:37

题目:回文链表(palindrome linklist)

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */typedef struct ListNode Node;void revers(Node *head);bool isPalindrome(struct ListNode* head) {    if(head==NULL || head->next==NULL)        return(true);    Node *slow=head,*fast=head;    while(fast->next!=NULL && fast->next->next!=NULL)//if not the tailender or the penultimate,go    {                                              /*how to find the middle?*/        fast=fast->next->next;        slow=slow->next;    }    revers(slow);//翻转后面的链表    Node *p=head;    if(slow!=NULL)//superfluous        slow=slow->next;    while(p!=NULL/*superfluous*/ &&slow!=NULL && slow->val==p->val)    {        slow=slow->next;        p=p->next;    }    if(slow==NULL)        return(true);    else        return(false);}void revers(Node *head){        if(head->next->next==NULL)            return;//一个节点        Node *p=head->next;        head->next=NULL;        Node *s=p;        while(p!=NULL)        {            s=s->next;            p->next=head->next;            head->next=p;            p=s;                 /*how to revers linklist without null pointer?*/        }}

思路总结:回文数的特征就是中间关于两边对称,就是从左向中间读和从右向中间读都是一样的,但是链表可以从左往右但是不能反过来。所以解题的关键就是如何反过来后面的链表,这里用到的方法是翻转后面的链表。

技巧积累与总结:①这里用到了快慢指针,主要目的是寻找链表的中间节点,fast和slow指针特点如下,当fast指针走到倒数第一个的时候,这个链表一定是odd sequence,如果是倒数第二个,一定是even sequence,并且,当fast指针在如上两个位置的时候,slow指针在链表的位置是可以推理得到的,是确定的,可以利用如上特别,find the middle of the linklist and revers it

②面向对象程序设计思想:模块化程序,可以方便调试,写出来的代码更不易错

③写注释和断言:注释和断言可以使得思路更加清晰,并且更利于调试

④写代码前要充分考虑各种情况,这是写好程序的基础

⑤翻转链表的方法的一个重点在于,如何不操作null pointer,只要让p=s next to the judgement p!=NULL即可

积累的单词总结:
null pointer 空指针
retrieve 恢复
revers 翻转
the last one 倒数第一个
penultimate 倒数第二个
superfluous 多余的,不必要的
quick question 小问题
optimal 最佳的
TEL 超时

原创粉丝点击