Flip linked list of Python data structure and flip of python Data Structure

Source: Internet
Author: User

Flip linked list of Python data structure and flip of python Data Structure

Flip a linked list

Example: A chain table 1-> 2-> 3-> null. The flipped chain table is 3-> 2-> 1-> null.

A simple method is to use the "removal" method ". It is to first create an empty node, then traverse the entire linked list, and point the nodes in turn to the first node of the new linked list.

For example, the steps are as follows:

1. Create an empty node: None
2. 1-> None
3. 2-> 1-> None
4. 3-> 2-> 1-> None

The code is very simple:

""" Definition of ListNode  class ListNode(object):   def __init__(self, val, next=None):   self.val = val   self.next = next """ class Solution:  """  @param head: The first node of the linked list.  @return: You should return the head of the reversed linked list.      Reverse it in-place.  """  def reverse(self, head):   temp = None   while head:    cur = head.next    head.next = temp    temp = head    head = cur   return temp   # write your code here 

Of course, there is a more difficult solution. We can write the code for in-situ turning by means of node chain extraction and link in the linked list:

"Definition of ListNode class ListNode (object): def _ init _ (self, val, next = None): self. val = val self. next = next "class Solution:" @ param head: The first node of the linked list. @ return: You shoshould return the head of the reversed linked list. reverse it in-place. "" def reverse (self, head): if head is None: return head dummy = ListNode (-1) dummy. next = head pre, cur = head, head. next while cur: temp = cur # link the link to pre. next = cur. next cur = pre. next temp. next = dummy. next dummy. next = temp return dummy. next # write your code here

Note that you should not forget to connect the removed part to the link during the chain extraction process.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.