C#:交换两个链表节点的实现方式及完整源码
在C#编程中,链表是一种非常常见的数据结构,经常需要对链表进行操作。其中一个常见的操作是交换链表中两个节点的位置。本文将介绍如何实现这个操作,同时提供完整的源代码。
首先,我们需要定义一个链表节点的类:
class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
接下来,我们可以使用以下方法实现交换链表中两个节点的位置:
public static ListNode SwapNodes(ListNode head, int k)
{
if (head == null || head.next == null) return head;
// Find the kth node from the beginning of the list
ListNode kthNodeFromBeginning = head;
for (int i = 1; i < k; i++)
{
kthNodeFromBeginning = kthNodeFromBeginning.next;
if (kthNodeFromBeginning == null) return head;
}
// Find the kth node from the end of the list
ListNode kthNodeFromEnd = head;
ListNode currentNode = head;
int count = 0;
while (currentNode != null)
{