Linked List and array in data structure (2)-simple operation problems on one-way linked list

Source: Internet
Author: User

This article mainly introduces some ideas and code implementation to solve some operation problems on the one-way linked list.

The main problems include:

1. Insert a node into the one-way linked list

2. delete a node in a one-way linked list

3. Search for a node in a one-way linked list

Expansion Question 1: Find the k-last node in the one-way linked list.

Expansion problem 2: Find the intermediate nodes in the one-way linked list. If the total number of nodes is an even number, the former (the latter) of the two intermediate elements is returned)

4. Reverse the one-way linked list (non-Recursive Implementation)

5. Reverse the one-way linked list (Recursive Implementation)

6. Determine whether a one-way linked list has a ring

7. Determine whether two one-way linked lists overlap

Expansion problem: returns the first intersection of two linked lists.

8. Stack is implemented using a single-chain table. the time complexity of push and pop is O (1)

9 using a single-chain table to implement a queue requires that the time complexity of enQueue and deQueue be O (1)

10 Delete the elements in another linked list in one linked list (I .e., the difference set (A-B ))

From the previous article, we can see that from the perspective of underlying data storage, the data structure can be divided into two types: sequential table (array) and linked list. Therefore, to master the data structure, you must first master the operations on arrays and linked lists.

In this article, we will first introduce some basic operations on linked lists.

A linked list can be displayed in multiple forms. It can be unidirectional or bidirectional, sorted or unordered, or annular or non-circular. The following describes some common operations on linked lists.

It is very practical to think twice before solving any problems in your life or computer. The problem can be easily solved only when you want to understand what to do and how to do it. If you don't even know what to do, the introduction to the success of the current actions will be very small. Therefore, when using computer coding to solve some problems, do not rush to coding. Instead, you must first think clearly about the ideas and points of attention, and then begin to implement your own ideas.

When dealing with linked lists, note the following:

1. always consider whether the pointer is null.

2. Do not point the pointer to invalid address spaces.

3. If there is no requirement, do not destroy the original structure of the linked list during the operation; if the structure of the linked list is damaged, it is a good method at present. After processing the data, remember to restore the original data structure of the linked list.

The following describes some common operations on one-way linked lists.

One-way linked list node definition:

Class SingleList

// Node definition on one-way linked list
Class SingleList
{
Public:
Int data;
SingleList * next; // pointer to the next node

SingleList ()
{
Next = NULL;
}
};

1. Insert a node into the one-way linked list

Ideas:1. Insert a node into the linked list.

Figure 1 insert a node

If you know a node pointer pre and a node pointer cur, You need to insert the cur into the pre node. Obviously, you need to ensure that the linked list will not be broken and the subsequent nodes will be lost, first, save the node pointer (pointer to lat), that is, cur-> next = pre-> next, and then connect a chain table connected by cur to the end of pre, that is, pre-> next = cur;

This section describes how to insert a node after a node. This is a common situation. To insert a node into the head of a linked list, you only need to direct the next pointer of the new node to the head pointer of the linked list.

In this case, pay attention to the following two points:

1. Whether the linked list is empty

2. Whether the node to be inserted is a null pointer.

Code implementation:

// Insert a node to the single-link table (insert at the beginning of the chain)
// Input parameter: the header pointer of the single-chain table and the node pointer to be inserted
// Output parameter: None
// Return value: the header pointer to a single-chain table
SingleList * Insert (SingleList * head, SingleList * node)
{
If (node = NULL)
{
Return head;
}
Else if (head = NULL)
{
Return node;
}

Node-> next = head;
Head = node;
Return head;
}

2. delete a node in a one-way linked list

Ideas:

Figure 2 deleting a node cur

As shown in figure 2, to delete a node cur is like removing a link from a chain that is linked together with the current ring. We only need to connect the previous ring to the next ring connected to the current ring.

To solve this problem, I only need to locate the pre of the previous node of the current node from the scratch list, and then set pre-> next = cur-> next. The time complexity of the delete operation is O (n ).

However, in some cases, if the time complexity must be O (1), what can we do? If the time complexity is required to be O (1), it is certainly not possible to traverse the chain table, but to perform a few small steps in the local area. So what can we do to delete it?

If the previous node of cur cannot be found, can we overwrite the current node value with the value of the last node like in the array and then delete the next node. Of course you can, as shown in 3. However, there is a limitation in this method, that is, if the node to be deleted is the end node, it cannot replace the deleted point, we can only search for the previous node based on the previous loop traversal.

Figure 3 delete node cur (when the header pointer is unknown)

When deleting nodes in a linked list, pay special attention to the first and last nodes of the linked list.

Code implementation:

SingleList * Delete (SingleList * head, SingleList * node)

// Delete a node from a single-chain table
// Input parameter: the header pointer of the single-chain table and the node to be deleted
// Output parameter: None
// Return value: the head pointer of the linked list.
SingleList * Delete (SingleList * head, SingleList * node)
{
SingleList * pSL;

// The linked list is empty or the node to be deleted is empty.
If (head = NULL) | (node = NULL ))
{
Return head;
}

// If the last node is not deleted
If (node-> next! = NULL)
{
PSL = node-> next;
Node-> next = node-> next;
Node-> data = pSL-> data;

Delete pSL;
PSL = NULL;

Return head;
}
// If the last node is deleted
Else
{
PSL = head;

While (pSL-> next! = NULL) & (pSL-> next! = Node ))
{
PSL = pSL-> next;
}
If (pSL-> next! = NULL)
{
PSL-> next = pSL-> next;
Delete node;
}
Return head;
}
}

3. Search for a node in a one-way linked list

Ideas:

This problem is simple. You only need to judge whether the node value is the value you want to find one by one from the beginning.

Code implementation:

ViSingleList * Select (SingleList * head, int data)

// Search for an element in a single-chain table
// Input parameter: the header pointer of the single-chain table and the element value to be searched
// Output parameter: None
// Return value: point to the node of the element or NULL
SingleList * Select (SingleList * head, int data)
{
While (head)
{
If (head-> data = data)
{
Return head;
}
Head = head-> next;
}
Return head;
}

Expansion Question 1: Find the k-last node in the one-way linked list.

Ideas:By traversing the common modes of searching the linked list, you may immediately think of a simple method: First traverse the chain table and check the number of nodes in the linked list. Assume that there are n nodes in the linked list, you need to find the last k, that is, the positive number n-k + 1. Next, you only need to go n-k steps from the beginning to the back. This method is executed about 2n-k times.

Is there any more efficient way than the above method? Open your mind, and do not fix it in a time series table with only one pointer. We can try to use multiple pointers to start a traversal table in different order.

For this problem, we can set two pointers. one pointer takes K steps on the linked list first, and the other pointer starts from the linked list header and goes backward with the previous pointer, in this way, when the first pointer reaches the end of the linked list, the second pointer will be at k points before the first pointer. At this time, the K-th node is found, and the number of algorithm executions is n times, which is 4 fewer than the previous method.

Figure 4 find the last k nodes

Code implementation:

GleList * returnNodeFromBack (SingleList * head, int k)

// Returns the pointer of the last K node in the linked list.
// Input parameter: the header pointer of the single-chain table, the reciprocal position of the node to be searched
// Output parameter: None
// Return value: the node pointer is returned for success, and NULL is returned for failure.
SingleList * returnNodeFromBack (SingleList * head, int k)
{
SingleList * firstPtr, * secondPtr;
Int count = 0;

FirstPtr = secondPtr = head;
While (firstPtr) & (count <k ))
{
FirstPtr = firstPtr-> next;
Count ++;
}

If (count <k)
{
Return NULL;
}

While (firstPtr)
{
FirstPtr = firstPtr-> next;
SecondPtr = secondPtr-> next;
}

Return secondPtr;
}

Expansion problem 2: Find the intermediate nodes in the one-way linked list. If the number of nodes is an even number, the former (the latter) of the two middle elements is returned)

Ideas:Similar to the first extension problem, we can first look for the intermediate elements, we can also take a look at the total number of nodes in the linked list, and then take half of the total number of nodes to find the intermediate element. Obviously, this method also involves traversing two linked lists.

So, can you refer to the above improvement methods to solve this problem. Of course, we can still use two traversal pointers in this case. Let the first pointer take two steps at a time, and the second pointer take one step at a time, because the number of nodes passing by the first pointer is twice that of the second pointer, so when the first pointer reaches the center point, the second pointer is in the center of the linked list.

Code Implementation:

SingleList * returnMidNode (SingleList * head)

// Return the intermediate node of the linked list
// Input parameter: the header pointer of a single-chain table
// Output parameter: None
// Return value: pointer or NULL of the intermediate node
SingleList * returnMidNode (SingleList * head)
{
SingleList * firstPtr, * secondPtr;
FirstPtr = secondPtr = head;

// There are no or only one node in the linked list
If (firstPtr = NULL) | (firstPtr-> next = NULL ))
{
Return firstPtr;
}

// While (firstPtr) & (firstPtr-> next) // if the number of even numbers is returned, the two indexes in the middle are relatively large.
While (firstPtr-> next) & (firstPtr-> next) // if the number of even numbers is returned, the two indexes in the middle are smaller.
{
FirstPtr = firstPtr-> next;
SecondPtr = secondPtr-> next;
}
Return secondPtr;
}

To promote the method, we can easily find the number at the first 1/3 position in the linked list.

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.