标签:
题目:
例如链表为1-->2-->3-->4,则交换后为:2-->1-->4-->3
代码:
#include <stdio.h> #include <stdlib.h> typedef struct ListNode { ListNode* next; int val; }; ListNode* swapNodeInPair(ListNode* head) { /*思路:直接交换*/ ListNode stHead = {0}; ListNode* pre; ListNode* cur; ListNode* next; stHead.next = head; pre = &stHead; cur = stHead.next; while (cur->next) { next = cur->next; cur->next = next->next; pre->next = next; next->next = cur; pre = cur; cur = cur->next; /*这里要注意,由于交换后,其实就跳过两个结点*/ } return stHead.next; } void createList(ListNode* head, int* num, int n) { ListNode* p; int i; for (i=0; i<n; i++) { p = (ListNode*)malloc(sizeof(ListNode)); p->next = head->next; p->val = num[i]; head->next = p; } } void printList(ListNode* head) { ListNode* p = head->next; while (p) { printf("%d ", p->val); p = p->next; } printf("\n"); } int main() { ListNode stHead = {0}; int a[] = {5, 4, 3, 2, 1}; createList(&stHead, a, 5); printList(&stHead); stHead.next = swapNodeInPair(stHead.next); printList(&stHead); return 0; }
标签:
原文地址:http://blog.csdn.net/yuanwei1314/article/details/43865499