Single Linked List is Palindrome or not

2020-02-28 07:00发布

I have a Single Linked List. I want to find that Linked List is Palindrome or not. I have implemented it in One way as below.

bool palindromeOrNot(node *head) {
  node *tailPointer;
  node *headLocal=head;
  node *reverseList=reverseLinkedListIteratively(head);
  int response=1;

  while(headLocal != NULL && reverseList!=NULL) {
    if(headLocal->id==reverseList->id) {
      headLocal=headLocal->next;
      reverseList=reverseList->next;
    }
    else
      return false;
  }

  if(headLocal == NULL && reverseList==NULL)
    return fasle;
  else 
    return true;
}

I am reversing the original Linked List and then comparing Node by Node. If everything is fine then I will return 1 else return 0.

Is there a better algorithm to solve the problem.

标签: linked-list
20条回答
虎瘦雄心在
2楼-- · 2020-02-28 07:14

How about having 2 pointers at the beginning of the link list.setting ptr1=k=start=1 and ptr2 =n where n is total number of nodes in linked list. We can then start with K and compare it with n-k+1 if both are same then increment k and go on comparing till we reach middle of the linked list

查看更多
手持菜刀,她持情操
3楼-- · 2020-02-28 07:15

This logic (Using Recursive) will work if you have two string objects in LinkedList.

public class LinkedList {
    Node head;
    String s1="",s2="";
    class Node{
        int data;
        Node next;
        Node(int d){
            this.data = d;
            this.next = null;
        }
    }
    public void append(int data){
        Node node = new Node(data);
        if(head==null){
            head = node;
        }else{
            Node cur = head;
            while(cur.next!=null) cur = cur.next;
            cur.next = node;
        }
    }
    public void palindrome(Node node){
        if(node==null){
            return;
        else
            s2+=""+node.data;
        palindrome(node.next);
        s1+=""+node.data;
    }
    public boolean isPalindrome(){
        palindrome(head);
        return s1.equals(s2);
    }
    public static void main(String ss[]){
       LinkedList  list = new LinkedList();
       list.append(10);
       list.append(25);
       list.append(10);
       System.out.println(list.isPalindrome());
   }
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-28 07:15

Just reverse half of the linked list. And start comparing. You don't need to reverse the whole linked list.

查看更多
Animai°情兽
5楼-- · 2020-02-28 07:16

METHOD 1 (Use a Stack)

A simple solution is to use a stack of list nodes. This mainly involves three steps.

  1. Traverse the given list from head to tail and push every visited node to stack.
  2. Traverse the list again. For every visited node, pop a node from stack and compare data of popped node with currently visited node.
  3. If all nodes matched, then return true, else false.

Time complexity of above method is O(n), but it requires O(n) extra space. Following methods solve this with constant extra space.

METHOD 2 (By reversing the list)

This method takes O(n) time and O(1) extra space.

  1. Get the middle of the linked list.
  2. Reverse the second half of the linked list.
  3. Check if the first half and second half are identical.
  4. Construct the original linked list by reversing the second half again and attaching it back to the first half

METHOD 3 (Using Recursion)

Use two pointers left and right. Move right and left using recursion and check for following in each recursive call.

  1. Sub-list is palindrome.
  2. Value at current left and right are matching.

If both above conditions are true then return true.

The idea is to use function call stack as container. Recursively traverse till the end of list. When we return from last NULL, we will be at last node. The last node to be compared with first node of list.

In order to access first node of list, we need list head to be available in the last call of recursion. Hence we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need reference to 2nd node from head. We advance the head pointer in previous call, to refer to next node in the list.

However, the trick in identifying double pointer. Passing single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of head pointer for reflecting the changes in parent recursive calls.

More: geeksforgeeks

查看更多
趁早两清
6楼-- · 2020-02-28 07:16

Whether a single-linked list is Palindrome or not, can also be checked without reversing the linked list

A recursive approach can be approached where a pointer pointing to the start of the linked list, & another pointer returning from the recursion from the last will be compared.

Here is the pseudo code:

int isPalindrome(**root,*head)
{
if(!head)
    return 1;
else
{
    int res = isPalindrome(root,head->next);

    if(res == 0)
        return 0;
    int r = (*root)->data == head->data;
    *root = (*root)->next;
    return r;
}
} 

Call is made like: isPalindrome(&root,root);

查看更多
Rolldiameter
7楼-- · 2020-02-28 07:17

I think the optimal solution would be to NOT using extra space, meaning NOT to use a new reversed LL... the idea is to take advantage of the operation stack that recursion uses... because when the recursion had reached the base case, it would start popping the stack from the last inserted node, which is the last node of the LL... I'm actually half way through this and hit a wall.. some how the root and the last node are offset... see my code

public LLNode compare(LLNode root) {
    // 
    // base case, popping opr stack,
    // this should be the last node on the linked list
    if (root.next == null) {
        System.out.printf("Poping stack: %d\n", root.data);
        return root;
    }

    // 
    // push the functions to the opr stack
    System.out.printf("pushing %d to the stack\n", root.next.data);
    LLNode last = compare(root.next);
    System.out.printf("On the way back: %d, root: %d\n", last.data, root.data);

    return root;
}

And the output looks like this:

The list looks like this:
1 2 3 4 3 2 1
pushing 2 to the stack
pushing 3 to the stack
pushing 4 to the stack
pushing 3 to the stack
pushing 2 to the stack
pushing 1 to the stack
Poping stack: 1
On the way back: 1, root: 2
On the way back: 2, root: 3
On the way back: 3, root: 4
On the way back: 4, root: 3
On the way back: 3, root: 2
On the way back: 2, root: 1

If you can figure it out, please let me know too

查看更多
登录 后发表回答