Write a Program to swap nodes in a singly linked list without swapping data
Solution:
using System;
namespace LinkedListOpearation
{
class Program
{
public static void Main()
{
var linkedList = new LinkedList();
linkedList.Add(6);
linkedList.Add(1);
linkedList.Add(5);
linkedList.Add(1);
linkedList.Add(3);
linkedList.Add(9);
Console.WriteLine("Sorted Linked List:");
linkedList.Print(linkedList.Head);
linkedList.Swap(5, 9);
Console.WriteLine("After swap Linked List:");
linkedList.Print(linkedList.Head);
Console.ReadLine();
}
}
public class LinkedList
{
public Node Head;
public int Size;
public void Add(int data)
{
var node = new Node(data) {Next = Head};
Head = node;
Size++;
}
public void Swap(int data1, int data2)
{
Node prevNode1 = null;
Node prevNode2 = null;
var node1 = Head;
var node2 = Head;
if (Head == null)
return;
if (data1 == data2)
return;
while (node1 != null && node1.Data != data1)
{
prevNode1 = node1;
node1 = node1.Next;
}
while (node2 != null && node2.Data != data2)
{
prevNode2 = node2;
node2 = node2.Next;
}
if (node1 == null || node2 == null) return;
if (prevNode1 != null)
prevNode1.Next = node2;
else
Head = node2;
if (prevNode2 != null)
prevNode2.Next = node1;
else
Head = node1;
var temp = node1.Next;
node1.Next = node2.Next;
node2.Next = temp;
}
public void Print(Node head)
{
while (head != null)
{
Console.WriteLine(head.Data);
head = head.Next;
}
}
}
public class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
}
}
}