两个指针分别从双链表的两端向中间遍历
奇数个节点时:p==q为出口
偶数个节点时:p->next=q为出口
编程注意事项:
不需要讨论奇数个节点还是偶数个节点,因为以上两种情况并不会同时出现。
typedef struct DLNode { int data; struct DLNode *next; struct DLNode *prior; }DLNode, *DLinkList; /*双链表*/ DLinkList DList_HeadInsert(DLinkList L) { int x; L = (DLinkList)malloc(sizeof(DLNode)); L->next = NULL; L->prior = NULL; DLNode *s, *r=L; cout << "尾插法创建双链表:"; while (true) { cin >> x; s = (DLNode*)malloc(sizeof(DLNode)); s->data = x; r->next = s; s->prior = r; r = s; if (cin.get() == '\n')break; } r->next = L; L->prior = r; return L; } void DList_Print(DLinkList L) { DLNode *p; p = L->next; cout << "正向输出:"; while (p!=L) { cout << p->data << " "; p = p->next; } cout << endl; p = L->prior; cout << "逆向输出:"; while (p!=L) { cout << p->data << " "; p = p->prior; } } bool Judge_Duichen(DLinkList L) { if (L->next == NULL || L->next->next == NULL)return true;//单链表为空或者只有一个元素时,默认为对称 DLNode *p,*q; p = L->next; q = L->prior; while (p!=q&&p->next!=q) { if (p->data == q->data) { p = p->next; q = q->prior; } else return false; } return true; } void seventeen() { DLinkList L = NULL; L = DList_HeadInsert(L); DList_Print(L); cout << endl; cout<<Judge_Duichen(L); } int main() { //第十七题: seventeen(); }