判断是否是回文链表

要求

判断一个链表是否是回文链表,例如:1->2->3->3->2->1->NULL 这是回文链表

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
//1,2,3,4,3,2,1  1,2,3,3,2,1
class Solution {
public:
    int lengthOfList(ListNode* head){
        ListNode* p = head;
        int count = 0;
        while (p!=NULL) {
            p = p->next;
            count++;
        }
        return count;
    }
    ListNode* reveseList(ListNode* head){
        ListNode* pre = head;
        ListNode* p = head->next;
        ListNode* next  = NULL;
        while (p!=NULL) {
            next = p->next;
            p->next = pre;
            pre = p;
            p = next;
        }
        head->next = NULL;
        return pre;
    }
    bool isPalindrome(ListNode* head) {
        if (head==NULL||head->next==NULL) {
            return true;
        }else{
            int len = lengthOfList(head);
            int half = len/2;
            ListNode* leftStart = head;
            ListNode* rightStart = head;
            if (len%2!=0) {
                half++;
            }
            for (int i=0; i<half; i++) {
                rightStart = rightStart->next;
            }
            rightStart = reveseList(rightStart);
            while (rightStart!=NULL) {
                if (leftStart->val==rightStart->val) {
                    leftStart = leftStart->next;
                    rightStart = rightStart->next;
                }else{
                    return false;
                }
            }
            return true;
        }

    }
};
int main(int argc, const char * argv[]) {

    return 0;
}

Comments