Ⅰ 判断一个链表是不是回文数,要求O(n)时间
1. 使用2个指针,快慢指针各一个,每次快指针移动一个,慢指针移动2个。 2. 当快指针不为NULL时候,将慢指针push到栈中。 3. 当快指针等于NULL时候,说明链表前半部分已经被压入栈中。 4. 每次栈Top元素与当前慢指针元素比较,如果不相等则返回false。如果相等,则栈Pop,慢指针++。 5. 链表奇数或者偶数节点需要判断。 #include <iostream #include <stack struct node{int data;node* next; node(int eData, node* eNext){data = eData; next = eNext;}}; bool isPanli(node* head){std::stack<node* stk; node* slow = head; node* fast = head; bool flag = false; while (fast){stk.push(slow); slow = slow-next; fast = fast-next;if (fast){fast = fast-next;}elseflag = true;}if (flag)stk.pop(); while (!stk.empty()){if (stk.top()-data == slow-data){stk.pop();slow = slow-next;}elsereturn false;} return true;};int main(){node* n5 = new node(1, NULL); node* n4 = new node(2, n5); node* n3 = new node(3, n4); //node* n2 = new node(3, n3);node* n1 = new node(2, n3);
Ⅱ C语言指针,判断是否是回文
参数应为char *p.
另外, strlen参数应为p而不是*p .
最后 虽然你这个修改后可以实现判断, 但严格来说内不算是利用指针实容现.
修改如下
#include<stdio.h>
intmain(void)
//判断字符串是否是回文
{
inti=0,flag;
charstr[80];
intyes(char*p);//
printf("请输入字符串:");
while((str[i]=getchar())!=' ')i++;
str[i]='