给定一个单向链表,编写函数交换相邻 两个元素
输入: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
输出: 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> 7
输入: 1 -> 2 -> 3 -> 4 -> 5 -> 6
输出: 2 -> 1 -> 4 -> 3 -> 6 -> 5
通过观察发现:当输入的与元素个数是单数的时候,最后一位不参与交换。
当链表节点中的数据字段不多的时候我们可以交换数据域的指针来实现相邻两个节点的交换。
当数据域太多时操作成本将非常昂贵,该情形下,更改链域(指针域)将是一个更好的解决方法。
以下是代码的实现:
时间复杂度:O(n)
c语言:
/*the program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls.*/#include#include
/*A linked list node*/
structNode {intindex;intdata;struct Node*next;
};/*function to pairwise swap elements of a linked list*/
void pairWiseSwap(struct Node**head_ref)
{//if linked list empty or there is only one node in list
if(*head_ref == NULL || (*head_ref)->next ==NULL)
{return;
}//initialize previous and current pointers
struct Node* previous = *head_ref;struct Node* current = (*head_ref)->next;//change head before proceeding
*head_ref =current;//Traverse the list
while(1)
{struct Node* next = current->next;//change next of current as previous node
current->next =previous;//if next NULL or next is last node
if(next == NULL || next->next ==NULL)
{
previous->next =next;break;
}//change next of previous to next next
previous->next = next->next;//update previous and current
previous =next;
current= previous->next;
}
}/*function to add a node at the beginning of Linked List*/
void push(struct Node** head_ref, int index,intnew_data)
{//allocate node
struct Node* new_node = (struct Node*)malloc(sizeof(structNode));//fill with the index
new_node->index =index;//put in the data
new_node->data =new_data;//link the old list of the new node
new_node->next = (*head_ref);//move the head to point to the new node
(*head_ref) =new_node;
}/*function to print nodes in a given linked list*/
void printList(struct Node*node)
{while(node !=NULL)
{
printf("(index %d)%d", node->index, node->data);
node= node->next;
}
printf("\n");
}/*driver program to test above function*/
intmain() {struct Node* start =NULL;/*the constructed linked list is:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7*/push(&start, 7, 7);
push(&start, 6, 6);
push(&start ,5, 5);
push(&start, 4, 4);
push(&start, 3, 3);
push(&start, 2, 2);
push(&start, 1, 1);
printf("Linked list before calling pairwise swap function\n");
printList(start);
pairWiseSwap(&start);
printf("Linked list after calling pairwise swap function\n");
printList(start);return 0;
}
java代码:
//Java program to swap elements of linked list by changing links
classLinkedList {staticNode head;static classNode {intdata;
Node next;
Node(intd)
{
data=d;
next= null;
}
}/*Function to pairwise swap elements of a linked list*/Node pairWiseSwap(Node node)
{//If linked list is empty or there is only one node in list
if (node == null || node.next == null) {returnnode;
}//Initialize previous and current pointers
Node prev =node;
Node curr=node.next;
node= curr; //Change head before proceeeding//Traverse the list
while (true) {
Node next=curr.next;
curr.next= prev; //Change next of current as previous node//If next NULL or next is the last node
if (next == null || next.next == null) {
prev.next=next;break;
}//Change next of previous to next next
prev.next =next.next;//Update previous and curr
prev =next;
curr=prev.next;
}returnnode;
}/*Function to print nodes in a given linked list*/
voidprintList(Node node)
{while (node != null) {
System.out.print(node.data+ " ");
node=node.next;
}
}//Driver program to test above functions
public static voidmain(String[] args)
{/*The constructed linked list is:
1->2->3->4->5->6->7*/LinkedList list= newLinkedList();
list.head= new Node(1);
list.head.next= new Node(2);
list.head.next.next= new Node(3);
list.head.next.next.next= new Node(4);
list.head.next.next.next.next= new Node(5);
list.head.next.next.next.next.next= new Node(6);
list.head.next.next.next.next.next.next= new Node(7);
System.out.println("Linked list before calling pairwiseSwap() ");
list.printList(head);
Node st=list.pairWiseSwap(head);
System.out.println("");
System.out.println("Linked list after calling pairwiseSwap() ");
list.printList(st);
System.out.println("");
}
}//This code has been contributed by Mayank Jaiswal
c#代码:
//C# program to swap elements of//linked list by changing links
usingSystem;public classLinkedList {
Node head;public classNode {public intdata;publicNode next;public Node(intd)
{
data=d;
next= null;
}
}/*Function to pairwise swap
elements of a linked list*/Node pairWiseSwap(Node node)
{//If linked list is empty or there//is only one node in list
if (node == null || node.next == null) {returnnode;
}//Initialize previous and current pointers
Node prev =node;
Node curr=node.next;//Change head before proceeeding
node =curr;//Traverse the list
while (true) {
Node next=curr.next;//Change next of current as previous node
curr.next =prev;//If next NULL or next is the last node
if (next == null || next.next == null) {
prev.next=next;break;
}//Change next of previous to next next
prev.next =next.next;//Update previous and curr
prev =next;
curr=prev.next;
}returnnode;
}/*Function to print nodes
in a given linked list*/
voidprintList(Node node)
{while (node != null) {
Console.Write(node.data+ " ");
node=node.next;
}
}//Driver code
public static voidMain(String[] args)
{/*The constructed linked list is:
1->2->3->4->5->6->7*/LinkedList list= newLinkedList();
list.head= new Node(1);
list.head.next= new Node(2);
list.head.next.next= new Node(3);
list.head.next.next.next= new Node(4);
list.head.next.next.next.next= new Node(5);
list.head.next.next.next.next.next= new Node(6);
list.head.next.next.next.next.next.next= new Node(7);
Console.WriteLine("Linked list before calling pairwiseSwap()");
list.printList(list.head);
Node st=list.pairWiseSwap(list.head);
Console.WriteLine("");
Console.WriteLine("Linked list after calling pairwiseSwap()");
list.printList(st);
Console.WriteLine("");
}
}//This code contributed by Rajput-Ji
递归法:
c语言:
/*This program swaps the nodes of linkd list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls*/#include#include
/*A linked list node*/
structNode
{intdata;struct Node*next;
};/*function to pairwise swap elements of a linked list.
it returns head of the modified list, so return value
of this node must be assigned*/
struct Node* pairWiseSwap(struct Node*head)
{//base case: the list is empty or has only one node
if(head == NULL || head->next ==NULL)returnhead;//store head of list after two nodes
struct Node* remaing = head->next->next;//chnage head
struct Node* newhead = head->next;//change next of second node
head->next->next =head;//recursive for remaining list and change next of head
head->next =pairWiseSwap(remaing);//Return new head of modified list
returnnewhead;
}/*function to add a node at the begining of Linked List*/
void push(struct Node** head_ref, intnew_data)
{//allocate node
struct Node* new_node = (struct Node*)malloc(sizeof(structNode));//puth in the data
new_node->data =new_data;/*link the old list off the new node*/new_node->next = (*head_ref);/*move the head to point to the new node*/(*head_ref) =new_node;
}/*function to print nodes in a given linked list*/
void printList(struct Node*node)
{while( node !=NULL )
{
printf("%d", node->data);
node= node->next;
}
printf("\n");
}/*Driver program to test above function*/
intmain()
{struct Node* start =NULL;/*the constructed linked list is
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7*/push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf("Linked List before calling pairWiseSwap function\n");
printList(start);//note this change
start =pairWiseSwap(start);
printf("Linked list after calling pairWiseSwap function\n");
printList(start);return 0;
}
结果:
java代码:
//Java program to swap elements of linked list by changing links
classLinkedList {staticNode head;static classNode {intdata;
Node next;
Node(intd)
{
data=d;
next= null;
}
}/*Function to pairwise swap elements of a linked list.
It returns head of the modified list, so return value
of this node must be assigned*/Node pairWiseSwap(Node node)
{//Base Case: The list is empty or has only one node
if (node == null || node.next == null) {returnnode;
}//Store head of list after two nodes
Node remaing =node.next.next;//Change head
Node newhead =node.next;//Change next of second node
node.next.next =node;//Recur for remaining list and change next of head
node.next =pairWiseSwap(remaing);//Return new head of modified list
returnnewhead;
}/*Function to print nodes in a given linked list*/
voidprintList(Node node)
{while (node != null) {
System.out.print(node.data+ " ");
node=node.next;
}
}//Driver program to test above functions
public static voidmain(String[] args)
{/*The constructed linked list is:
1->2->3->4->5->6->7*/LinkedList list= newLinkedList();
list.head= new Node(1);
list.head.next= new Node(2);
list.head.next.next= new Node(3);
list.head.next.next.next= new Node(4);
list.head.next.next.next.next= new Node(5);
list.head.next.next.next.next.next= new Node(6);
list.head.next.next.next.next.next.next= new Node(7);
System.out.println("Linked list before calling pairwiseSwap() ");
list.printList(head);
head=list.pairWiseSwap(head);
System.out.println("");
System.out.println("Linked list after calling pairwiseSwap() ");
list.printList(head);
System.out.println("");
}
}
c#
//C# program to swap elements//of linked list by changing links
usingSystem;public classLinkedList {
Node head;classNode {public intdata;publicNode next;public Node(intd)
{
data=d;
next= null;
}
}/*Function to pairwise swap
elements of a linked list.
It returns head of the modified
list, so return value of this
node must be assigned*/Node pairWiseSwap(Node node)
{//Base Case: The list is empty//or has only one node
if (node == null || node.next == null) {returnnode;
}//Store head of list after two nodes
Node remaing =node.next.next;//Change head
Node newhead =node.next;//Change next of second node
node.next.next =node;//Recur for remaining list//and change next of head
node.next =pairWiseSwap(remaing);//Return new head of modified list
returnnewhead;
}/*Function to print nodes in a given linked list*/
voidprintList(Node node)
{while (node != null) {
Console.Write(node.data+ " ");
node=node.next;
}
}//Driver program to test above functions
public static voidMain()
{/*The constructed linked list is:
1->2->3->4->5->6->7*/LinkedList list= newLinkedList();
list.head= new Node(1);
list.head.next= new Node(2);
list.head.next.next= new Node(3);
list.head.next.next.next= new Node(4);
list.head.next.next.next.next= new Node(5);
list.head.next.next.next.next.next= new Node(6);
list.head.next.next.next.next.next.next= new Node(7);
Console.WriteLine("Linked list before calling pairwiseSwap()");
list.printList(list.head);
list.head=list.pairWiseSwap(list.head);
Console.WriteLine("");
Console.WriteLine("Linked list after calling pairwiseSwap()");
list.printList(list.head);
Console.WriteLine("");
}
}//This code is contributed by PrinciRaj1992
其他参考: